【问题标题】:flutter download an Image from url颤振从网址下载图片
【发布时间】:2019-02-17 07:51:19
【问题描述】:

我正在尝试使用 networkimage() 从服务器加载图像,并且我想在加载后下载相同的图像.. 谁能给我一些建议。

CircleAvatar(
      backgroundImage: NetworkImage(url),
      maxRadius: 15.0,
              ); 

在这里,我正在从我的服务器加载图像。我想在图像加载后将图像保存到特定路径。

【问题讨论】:

标签: flutter


【解决方案1】:

我使用这个插件通过 URL 将图像保存在手机中 https://pub.dartlang.org/packages/image_picker_saver

【讨论】:

    【解决方案2】:

    我推荐image_downloader

    • 对于 ios,图片保存在照片库中。
    • 对于Android,图像保存在Environment.DIRECTORY_DOWNLOADS 或指定位置。通过调用inExternalFilesDir(),无需指定权限。
    • 通过callback(),您可以获得进度状态。

    下面是最简单的例子。它将被保存。

    await ImageDownloader.downloadImage(url);
    

    【讨论】:

    • iOS 照片库是私有的吗?或者那里的照片会在用户的图库应用中成为垃圾邮件?
    【解决方案3】:

    要更高级地处理图像/文件下载,您可以考虑使用flutter_downloader 包。

    我喜欢的一些功能是:

    • 显示操作系统级别的下载进度
    • 可以跟踪所有下载
    • 有通知

    【讨论】:

    • 如何使用flutter_downloader保存到iOS Photos App?可以分享一下sn-p吗?
    【解决方案4】:

    我最近解决了这个问题,并决定在没有插件的情况下解决它。我希望它可以帮助某人。

    下面的程序从网上下载一张图片,存储在设备的本地路径中,运行时显示出来。 (注意,它不适用于 Flutter Web,因为您无法访问该平台上的本地文件存储。相反,您必须使用 sqflite 之类的插件或来自 pub.dev 的 hive 将图像保存到本地数据库.) 这是代码:

    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 {
      // This widget is the root of your application.
      @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<MyHomePage> {
      @override
      initState() {
        _asyncMethod();
        super.initState();
      }
    
      _asyncMethod() async {
        //comment out the next two lines to prevent the device from getting
        // the image from the web in order to prove that the picture is 
        // coming from the device instead of the web.
        var url = "https://www.tottus.cl/static/img/productos/20104355_2.jpg"; // <-- 1
        var response = await get(url); // <--2
        var documentDirectory = await getApplicationDocumentsDirectory();
        var firstPath = documentDirectory.path + "/images";
        var filePathAndName = documentDirectory.path + '/images/pic.jpg'; 
        //comment out the next three lines to prevent the image from being saved
        //to the device to show that it's coming from the internet
        await Directory(firstPath).create(recursive: true); // <-- 1
        File file2 = new File(filePathAndName);             // <-- 2
        file2.writeAsBytesSync(response.bodyBytes);         // <-- 3
        setState(() {
          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: <Widget>[
                  Image.file(File(imageData), width: 600.0, height: 290.0)
                ],
              ),
            ),
          );
        } else {
          return CircularProgressIndicator(
            backgroundColor: Colors.cyan,
            strokeWidth: 5,
          );
        }
      }
    }
    

    pubspec.yaml 文件: http: ^0.12.1 path_provider: ^1.6.5

    颤振版本:1.20.0-3.0.pre.112 飞镖版本 2.9.0-19.0.dev

    【讨论】:

    • 因此,这适用于特定文件,因为您为文件指定了特定名称,因此无需再次下载即可调用它。我想知道是否可以写一些更通用的东西,以便我可以处理多个图像。比方说一个聊天应用程序。我不想多次下载图像。此外,它必须是无状态的,因为我不想在关闭应用后再次下载图像。
    【解决方案5】:

    我用过image_downloader
    使用image_downloader 包的await ImageDownloader.downloadImage("url") 方法,通过它的url 下载图片。

    注意:上述方法将返回值如下:-

    • 如果保存成功则保存图片的imageId。

    • 如果没有被授予权限则为空。 为此,您必须请求存储权限,只需在 android manifest 文件中添加以下行:

    使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE"

    • 否则是 PlatformException。

    【讨论】:

      【解决方案6】:

      我尝试了很多解决方案,但这对我来说是最简单的解决方案……试试吧

      步骤 - 1
      将此包添加到您的 pubspec.yaml 文件中

      dependencies:
       image_downloader: ^0.20.1
      

      步骤 - 2
      将此添加到您的 dart 文件中

      import 'package:image_downloader/image_downloader.dart';  
      

      步骤 - 3
      按下download按钮写下这段代码

      ColButton(
         title: 'Download',
         icon: Icons.file_download,
         onTap: () async {
           try {
             showLoadingDialog(context);
             // Saved with this method.
             var imageId =
                 await ImageDownloader.downloadImage("https://raw.githubusercontent.com/wiki/ko2ic/image_downloader/images/bigsize.jpg");
             if (imageId == null) {
                return;
             }
             // Below is a method of obtaining saved image information.
             var fileName = await ImageDownloader.findName(imageId);
             var path = await ImageDownloader.findPath(imageId);
             var size = await ImageDownloader.findByteSize(imageId);
             var mimeType = await ImageDownloader.findMimeType(imageId);
             Navigator.pop(context);
             showToast('Image downloaded.');
            } on PlatformException catch (error) {
                print(error);
              }
           },
         ),
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 2016-04-01
        • 2020-12-12
        • 2021-02-19
        相关资源
        最近更新 更多