有没有办法将资产图像用作文件。我需要一个文件,以便它可以用于使用 http 在 Internet 上进行测试。我已经尝试了 Stackoverflow.com 的一些答案(如何使用 image.file 加载图像)但收到错误“无法打开文件,(操作系统错误:没有这样的文件或目录,errno = 2)”。附加的代码行也给出了错误。
File f = File('images/myImage.jpg');
RaisedButton(
onPressed: ()=> showDialog(
context: context,
builder: (_) => Container(child: Image.file(f),)),
child: Text('Show Image'),)
Run Code Online (Sandbox Code Playgroud)
使用 Image.memory 小部件(有效)
Future<Null> myGetByte() async {
_byteData = await rootBundle.load('images/myImage.jpg');
}
/// called inside build function
Future<File> fileByte = myGetByte();
/// Show Image
Container(child: fileByte != null
? Image.memory(_byteData.buffer.asUint8List(_byteData.offsetInBytes, _
byteData.lengthInBytes))
: Text('No Image File'))),
Run Code Online (Sandbox Code Playgroud)
cre*_*not 35
您可以通过访问字节数据rootBundle。然后,您可以将其保存到通过path_provider(需要将其添加为依赖项)获取的设备的临时目录中。
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您可以这样调用此函数:
File f = await getImageFileFromAssets('images/myImage.jpg');
Run Code Online (Sandbox Code Playgroud)
有关写入字节数据的更多信息,请查看此答案。
您需要await的Future,为了做到这一点,使功能async:
RaisedButton(
onPressed: () async => showDialog(
context: context,
builder: (_) => Container(child: Image.file(await getImageFileFromAssets('images/myImage.jpg')))),
child: Text('Show Image'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25440 次 |
| 最近记录: |