扑从URL下载图像 [英] flutter download an Image from url

查看:67
本文介绍了扑从URL下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用networkimage()从服务器加载图像,并且一旦加载就想下载该图像.任何人都可以向我提出一些建议.

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.

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.

以下程序从网上下载图片,将其存储在设备的本地路径中,然后在运行时显示.(请注意,它不适用于Flutter Web,因为您无权访问该平台上的本地文件存储.相反,您必须使用sqflite之类的插件将图像保存到本地数据库,或者从pub.dev中进行配置.这是代码:

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:

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路径提供者:^ 1.6.5

pubspec.yaml file: http: ^0.12.1 path_provider: ^1.6.5

Flutter版本:1.20.0-3.0.pre.112dart版本2.9.0-19.0.dev

flutter version: 1.20.0-3.0.pre.112 dart version 2.9.0-19.0.dev

这篇关于扑从URL下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆