Flutter save a network image to local directory

后端 未结 10 609
情歌与酒
情歌与酒 2020-12-24 08:52

In Flutter how to save an image from network to the local directory.

I am new to encoding and decoding images. Can anyone point me in the right direction?

10条回答
  •  隐瞒了意图╮
    2020-12-24 09:51

    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

    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 get _localPath async {
        final directory = await getApplicationDocumentsDirectory();
    
        return directory.path;
      }
       Future getImageFromNetwork(String url) async {
    
         var cacheManager = await CacheManager.getInstance();
         Io.File file = await cacheManager.getFile(url);
         return file;
       }
    
       Future 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

    class HomePageState extends State{
    
    Future _launched ;
    
      Widget _showResult(BuildContext context, AsyncSnapshot snapshot){
        if(!snapshot.hasError){
          return Text('Image is saved');
        }
        else{
          return const Text('Unable to save image');
        }
      }
    
      Future _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: [
                           IconButton(icon: Icon(Icons.save), onPressed: (){
                         setState(() {
                           _launched =_saveNetworkImage(url);
                         });
                        }),
                          new FutureBuilder(future: _launched ,builder: _showResult),
                      ],
                ),
              );
       }
    }
    

提交回复
热议问题