简体   繁体   English

颤动从 url 下载图像

[英]flutter download an Image from url

I'm trying to load image from server using networkimage() and I want to download the same once it is loaded.. can anyone suggest me some ideas.我正在尝试使用 networkimage() 从服务器加载图像,并且我想在加载后下载相同的图像..任何人都可以给我一些想法。

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

Here I'm loading image from my server.在这里,我正在从我的服务器加载图像。 I want to save to the image to particular path after the image is loaded.我想在加载图像后将图像保存到特定路径。

I recently battled this, and decided to solve it without plugins.我最近与这个问题作斗争,并决定在没有插件的情况下解决它。 I hope it helps someone.我希望它可以帮助某人。

The below program downloads a picture from the web, stores it in the device's local path, and then displays it when run.下面的程序从网上下载一张图片,存储在设备的本地路径中,然后在运行时显示它。 (note, it does not work for flutter web because you don't have access to the local file storage on that platform. Instead you would have to save the image to a local database using a plugin like sqflite, or hive from pub.dev.) Here's the code: (注意,它不适用于 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 file: http: ^0.12.1 path_provider: ^1.6.5 pubspec.yaml 文件:http:^0.12.1 path_provider:^1.6.5

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

I recommendimage_downloader .我推荐image_downloader

  • For ios, image is saved in Photo Library.对于 ios,图像保存在照片库中。
  • For Android, image is saved in Environment.DIRECTORY_DOWNLOADS or specified location.对于 Android,图像保存在Environment.DIRECTORY_DOWNLOADS或指定位置。 By calling inExternalFilesDir() , specification of permission becomes unnecessary.通过调用inExternalFilesDir() ,权限规范变得不必要。
  • By callback() , you can get progress status.通过callback() ,您可以获得进度状态。

The following is the simplest example.下面是最简单的例子。 It will be saved.它将被保存。

await ImageDownloader.downloadImage(url);

I used image_downloader .我使用了image_downloader
Use await ImageDownloader.downloadImage("url") of image_downloader package's method to download image using it's url.使用image_downloader包方法的await ImageDownloader.downloadImage("url")使用它的 url 下载图像。

Note : above method will return value as follows :-注意:上述方法将返回如下值:-

  • imageId of the saved image if saving succeeded.如果保存成功,则保存图像的 imageId。

  • null if not been granted permission.如果未获得许可,则为 null。 for this you have to ask for storage permission, just add following line into android manifest file :为此,您必须请求存储权限,只需将以下行添加到 android 清单文件中:

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

  • Otherwise it is a PlatformException.否则它是一个 PlatformException。

我使用此插件使用 URL https://pub.dartlang.org/packages/image_picker_saver在手机中保存图像

For more advanced handling of Image/File downloads, you can consider the flutter_downloader package.对于图像/文件下载的更高级处理,您可以考虑flutter_downloader包。

Some of the features that I like are :我喜欢的一些功能是:

  • Shows OS level download progress显示操作系统级下载进度
  • can track all downloads可以跟踪所有下载
  • Has notification有通知

I tried many solution, but this is simplest solution for my... Just try it我尝试了很多解决方案,但这是对我来说最简单的解决方案......试试吧

STEP - 1第1步
Add this package in your pubspec.yaml file在你的pubspec.yaml文件中添加这个包

dependencies:
 image_downloader: ^0.20.1

STEP - 2第2步
Add this in your dart file将此添加到您的dart文件中

import 'package:image_downloader/image_downloader.dart';  

STEP - 3步骤 - 3
Write this code on press download button在按下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);
        }
     },
   ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM