我正在从Internet下载图片并将其保存在平台目录中。
我从path_provider和(await getApplicationDocumentsDirectory()).path
获取平台的目录。
在iOS上,效果很好,但在Android上,我总是得到Unable to load asset: <path_to_my_directory>
。
编辑:我第一次启动时遇到此错误,热重启后,它运行得很好...
这是要测试的代码示例:
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool dataLoaded = false;
String pathToSave;
@override
void initState() {
downloadImage();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: dataLoaded ? getImageBody() : CircularProgressIndicator()
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
getImageBody() {
return Image.asset(pathToSave);
}
void downloadImage() async {
String url = 'https://github.githubassets.com/images/modules/open_graph/github-mark.png';
pathToSave = '${(await getApplicationDocumentsDirectory()).path}/github-mark.png';
await Dio().download(url, pathToSave);
print(pathToSave);
setState(() {
dataLoaded = true;
});
}
}
依赖项:
path_provider: ^1.6.11
dio: ^3.0.9
答案 0 :(得分:0)
对于遇到类似问题的所有人: