我有一个文本文件(.txt),我想成为一个资产,我可以在以后扫描.
在pubspec.yaml中,我确保:
flutter:
assets:
- res/my_file.txt
Run Code Online (Sandbox Code Playgroud)
存在.该文件位于res/我创建的文件夹中,与lib/android/和的级别相同ios/
我正在尝试从自定义类中读取文件,而不是小部件.
根据文档,我将使用此导入:
import 'package:flutter/services.dart' show rootBundle;
Run Code Online (Sandbox Code Playgroud)
并开始阅读:
/// Assumes the given path is a text-file-asset.
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Run Code Online (Sandbox Code Playgroud)
要获得实际数据,请执行以下操作:
String data = await getFileData(fileName);
Run Code Online (Sandbox Code Playgroud)
但是,当我使用fileNamelike时'assets/res/my_file.txt',我收到一个错误:Unable to load asset: assets/res/my_file.txt.
值得注意的是,我正试图通过单元测试来做到这一点.关于如何正确地做到这一点的任何想法?谢谢!
我有一个带有“assets”文件夹的模块,该文件夹与我的 pubspec.yaml 文件位于同一目录中。在我的资产文件夹中,我有 test.txt 和 simpleObject.json。
flutter:
assets:
- assets/test.txt
- assets/simpleObject.json
Run Code Online (Sandbox Code Playgroud)
我相信以下代码应该允许我将其读入我的应用程序。
var test = await DefaultAssetBundle.of(context).loadString("assets/test.txt");
Run Code Online (Sandbox Code Playgroud)
可悲的是,我收到以下错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:无法加载资产:assets/test.txt
错误来自于 asset_bundle.dart。我必须假设这是我的错,但根据我读过的所有内容,我做对了。有什么想法吗?
如果有帮助,这是我的文件结构。
MyModule
|_assets/test.txt
|_lib/
|_pubspec.yaml
Run Code Online (Sandbox Code Playgroud) 我在我的颤振应用程序上加载图像,如下所示:
Image.asset(imageFilePath, fit: BoxFit.cover)
Run Code Online (Sandbox Code Playgroud)
当我第一次在模拟器上运行应用程序时,我收到以下异常:
我/扑(7194):???图像资源服务捕获的异常 ???????????????????????????????????????????????? ????????? I/flutter (7194):以下断言被抛出解析图像编解码器:I/flutter (7194):无法加载资产:/data/user/0/com.example.myapp/app_flutter/888cba5135c38f7d.jpg ...
图片路径正确,文件存在。
如果我重新运行应用程序(单击
按钮),应用程序无一例外地加载,图像看起来很好。
可能是什么问题?
笔记:
flutter doctor 说一切都很好我无法将图像作为背景上传到容器,我已将图像添加到资产文件夹中并将其添加到 pubspec.yaml 并向我显示该错误:
I/flutter ( 6664): ??? EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ?????????????????????????????????????????????????????
I/flutter ( 6664): The following assertion was thrown resolving an image codec:
I/flutter ( 6664): Unable to load asset: assets/images/img.png
I/flutter ( 6664):
I/flutter ( 6664): When the exception was thrown, this was the stack:
I/flutter ( 6664): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
I/flutter ( 6664): <asynchronous suspension>
I/flutter ( 6664): #1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
I/flutter ( 6664): #2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
I/flutter ( 6664): #3 ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> …Run Code Online (Sandbox Code Playgroud)