Flutter找不到txt文件
我正在尝试使用 ini package 以读取文件,但是当我尝试尝试时要仅通过阅读其内容访问该文件,我会收到以下错误:没有此类文件或目录。
这是错误的代码:
class _FactsListScreenState extends State<FactsListScreen> {
@override
Widget build(BuildContext context) {
File file = File("Assets/Facts/English.txt");
Config config = Config.fromStrings(file.readAsLinesSync());
print(config.sections());
有趣,但是使用rootbundle.loadstring(“资产/facts/English.txt”)
它可以使用,但是当使用file(“资产/事实/英语)时。
是的,我已经在pubspec.yaml中包含了文件夹:
。
为什么找不到文件?
I'm trying to use the INI Package to read a file, but when I'm trying to access the file just by reading its contents I get the following error: No such file or directory.
Here is the faulty code:
class _FactsListScreenState extends State<FactsListScreen> {
@override
Widget build(BuildContext context) {
File file = File("Assets/Facts/English.txt");
Config config = Config.fromStrings(file.readAsLinesSync());
print(config.sections());
Interesting, but when using rootBundle.loadString("Assets/Facts/English.txt")
it works, but not when using File("Assets/Facts/English.txt")
I also need to mention that I'm running the app on an Android simulator, if that makes any difference.
Yes, I have included the folder in pubspec.yaml:
Here is my file structure to show that the file is actually there:
What's the problem with the code? Why it can't find the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法使用 File 从资产中读取文件,因为 File 是对文件系统上文件的引用。您无法通过文件访问资产文件。
每当您尝试调用时,
它都会尝试从设备而不是应用程序的资产文件夹中读取文件。
您可以使用以下函数从资产创建文件。
You can't use File to read files from assets due to File is a reference to a file on the file system. You can't access assets files by File.
Whenever you tried calling like
it will try to read files from a device not from the app's assets folder.
You could use the below function to make file from assets.
您可以将您的PubSpec文件更改为:
资产/
,然后致电:
file file = file(“ facts/English.txt”);
You can change your pubspec file to only:
Assets/
And then call:
File file = File("Facts/English.txt");
将您的Asset目录重命名为assets(小写)。因为根据 flutter 官方文档(使用 lowercase_with_underscores.fileextension 命名库、包、目录和源文件)检查此 链接供参考。
因此,在您的情况下,请执行以下操作:
使用字符串文件路径,如瘦
'assets/facts/english.txt'
Rename your Asset directory to assets (small case). because as per the flutter official document (name libraries, packages, directories, and source files using lowercase_with_underscores.fileextension)check this link for reference.
so in your case do following things:
use string file path like thin
'assets/facts/english.txt'