我正在尝试使用 networkimage() 从服务器加载图像,并且我想在加载后下载相同的图像..任何人都可以给我一些想法。
CircleAvatar(
backgroundImage: NetworkImage(url),
maxRadius: 15.0,
);
Run Code Online (Sandbox Code Playgroud)
在这里,我正在从我的服务器加载图像。我想在加载图像后将图像保存到特定路径。
Wil*_*ill 32
我最近与这个问题作斗争,并决定在没有插件的情况下解决它。我希望它可以帮助某人。
下面的程序从网上下载一张图片,存储在设备的本地路径中,然后在运行时显示它。(注意,它不适用于 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,
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
pubspec.yaml 文件:http:^0.12.1 path_provider:^1.6.5
颤振版本:1.20.0-3.0.pre.112 飞镖版本 2.9.0-19.0.dev
我推荐image_downloader。
Environment.DIRECTORY_DOWNLOADS或指定位置。通过调用inExternalFilesDir(),就不再需要指定权限。callback(),您可以获取进度状态。下面是最简单的例子。它将被保存。
await ImageDownloader.downloadImage(url);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32512 次 |
| 最近记录: |