Flutter save a network image to local directory

后端 未结 10 651
情歌与酒
情歌与酒 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:38

    I had a lot of trouble doing this, so I wanted to expound a little on the above answers with a simple example that downloads a file on startup, saves it to a local directory. I marked a couple of lines with the comment //%%% to show lines that can be commented out the second time that the app runs. (because it doesn't need to be downloaded to be displayed... it's already on the device itself:

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' show get;
    import 'dart:io';
    import 'package:path_provider/path_provider.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Test Image',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Test Image'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      @override
      initState() {
        _downloadAndSavePhoto();
        super.initState();
      }
    
      _downloadAndSavePhoto() async {
        // Get file from internet
        var url = "https://www.tottus.cl/static/img/productos/20104355_2.jpg"; //%%%
        var response = await get(url); //%%%
        // documentDirectory is the unique device path to the area you'll be saving in
        var documentDirectory = await getApplicationDocumentsDirectory();
        var firstPath = documentDirectory.path + "/images"; //%%%
        //You'll have to manually create subdirectories
        await Directory(firstPath).create(recursive: true); //%%%
        // Name the file, create the file, and save in byte form.
        var filePathAndName = documentDirectory.path + '/images/pic.jpg';
        File file2 = new File(filePathAndName); //%%%
        file2.writeAsBytesSync(response.bodyBytes); //%%%
        setState(() {
          // When the data is available, display it
          imageData = filePathAndName;
          dataLoaded = true;
        });
      }
    
      String imageData;
      bool dataLoaded = false;
    
      @override
      Widget build(BuildContext context) {
        if (dataLoaded) {
          return Scaffold(
            appBar: AppBar(
              title: Text(widget.title),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // imageData holds the path AND the name of the picture.
                  Image.file(File(imageData), width: 600.0, height: 290.0)
                ],
              ),
            ),
          );
        } else {
          return CircularProgressIndicator(
            backgroundColor: Colors.cyan,
            strokeWidth: 5,
          );
        }
      }
    }
    

    And heres my pubspec.yaml file:

    http: ^0.12.0+2
      path_provider: 1.5.0
    

提交回复
热议问题