Unable to load asset (file the app created)

﹥>﹥吖頭↗ 提交于 2021-01-29 11:10:11

问题


Why does this cause a crash?

final directory = await getApplicationDocumentsDirectory();
final testFile = File("${directory.path}/test.txt");
await testFile.writeAsString("Hello there!", flush: true);
final ByteData bytes = await rootBundle.load(testFile.path);

The rootBundle.load() call causes:

Unhandled Exception: Unable to load asset: /data/user/0/com.flutter.tests/app_flutter/test.txt

BUT if I do a hot reload then it works fine until I restart the app.

I have a dependency path_provider: any in pubspec.yaml which is needed for the getApplicationDocumentsDirectory().


回答1:


rootBundle only contains assets that were specified by pubspec.yaml and were built with your application. It's not supposed to access files created within file system. Use File or Image classes to open created files.

final bytes = testFile.readAsBytesSync();

The rootBundle contains the resources that were packaged with the application when it was built. To add resources to the rootBundle for your application, add them to the assets subsection of the flutter section of your application's pubspec.yaml manifest.



来源:https://stackoverflow.com/questions/58712261/unable-to-load-asset-file-the-app-created

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!