flutter download an Image from url

57hvy0tb  于 2023-04-22  发布在  Flutter
关注(0)|答案(7)|浏览(121)

我试图从服务器使用networkimage()加载图像,我想下载相同的,一旦它被加载..任何人都可以建议我一些想法。

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

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

pgccezyw

pgccezyw1#

我最近与此作斗争,并决定在没有插件的情况下解决它。我希望它能帮助到一些人。
下面的程序从网络下载图片,将其存储在设备的本地路径中,然后在运行时显示它。(注意,它不适用于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
Flutter版本:1.20.0-3.0.pre.112 dart版本2.9.0-19.0.dev

nqwrtyyt

nqwrtyyt2#

我推荐image_downloader。

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

以下是最简单的示例。它将被保存。

await ImageDownloader.downloadImage(url);
rvpgvaaj

rvpgvaaj3#

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

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

  • 保存成功时保存的图像的imageId。
  • null如果没有被授予权限.为此,你必须要求存储权限,只需添加以下行到Android清单文件:

uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”

  • 否则,它是一个PlatformException。
yzuktlbb

yzuktlbb4#

我尝试了很多解决方案,但这是最简单的解决方案,为我...只是尝试它
步骤-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);
        }
     },
   ),
3ks5zfa0

3ks5zfa05#

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

3qpi33ja

3qpi33ja6#

对于更高级的图像/文件下载处理,您可以考虑flutter_downloader包。
我喜欢的一些功能是:

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

2ekbmq327#

当使用image_downloader时,如果有人得到了这个

Error : (No implementation found for method downloadImage on channel plugins.ko2ic.com/image_downloader)

而不是遵循以下步骤
注意:在Android的情况下,要使用此功能,需要进行以下设置。
在AndroidManifest.xml中的标签内添加以下内容。

<provider
        android:name="com.ko2ic.imagedownloader.FileProvider"
        android:authorities="${applicationId}.image_downloader.provider"
        android:exported="false"
        android:grantUriPermissions="true">
    <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
</provider>

在android/app/src/main/res/xml/中添加provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

相关问题