If you want to save a network image to local directory in flutter? After wandering around the codes and flutter docs. I have found the methods and classes which would work for both iOS and Android and here it goes.
Helper Classs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import 'dart:async'; import 'dart:io' as Io; import 'package:image/image.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:path_provider/path_provider.dart'; class SaveFile { Future<String> get _localPath async { final directory = await getApplicationDocumentsDirectory(); return directory.path; } Future<Io.File> getImageFromNetwork(String url) async { var cacheManager = await CacheManager.getInstance(); Io.File file = await cacheManager.getFile(url); return file; } Future<Io.File> saveImage(String url) async { final file = await getImageFromNetwork(url); //retrieve local path for device var path = await _localPath; Image image = decodeImage(file.readAsBytesSync()); Image thumbnail = copyResize(image, 120); // Save the thumbnail as a PNG. return new Io.File('$path/${DateTime.now().toUtc().toIso8601String()}.png') ..writeAsBytesSync(encodePng(thumbnail)); } } |
Usage of class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class HomePageState extends State<HomePage>{ Future<Null> _launched ; Widget _showResult(BuildContext context, AsyncSnapshot<Null> snapshot){ if(!snapshot.hasError){ return Text('Image is saved'); } else{ return const Text('Unable to save image'); } } Future<Null> _saveNetworkImage(String url) async{ try{ await SaveFile().saveImage(url); } on Error catch(e){ throw 'Error has occured while saving'; } } @override Widget Build(BuildContext context){ return new Scaffold( key: _scaffoldKey, appBar: new AppBar( title: new Text('Image'), ), body: Column( children: <Widget>[ IconButton(icon: Icon(Icons.save), onPressed: (){ setState(() { _launched =_saveNetworkImage(url); }); }), new FutureBuilder<Null>(future: _launched ,builder: _showResult), ], ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.