[英]Can't read files in Flutter on all platforms, the file can be seen on linux desktop but web(chrome) does not see it, nor does android
import 'dart:io';
import 'package:path/path.dart';
Future<Map?> readFile(lang) async {
var pathToFile = join(dirname(Platform.script.toFilePath()), 'text', '$lang.toml');
var document = File(pathToFile);
return document;
}
So I have a text directory in my flutter root directory which contains some TOML files, I have no trouble accessing these files on linux but as soon as I run this on android I get a (OS Error: No such file or directory, errno = 2)
, and same on web but without the error message, it just returns null, I have also tried this as well:所以我的 flutter 根目录中有一个文本目录,其中包含一些 TOML 文件,我在 linux 上访问这些文件没有问题,但是一旦我在 android 上运行它,我就会得到一个(OS Error: No such file or directory, errno = 2)
, 和 web 上一样,但没有错误消息,它只返回 null,我也试过这个:
var document = File('text/$lang.toml');
once again, same result.再一次,同样的结果。 I have seen people use the path_provider package for this but it didn't work anyway, and I would also like to have web compatibility.我已经看到人们为此使用 path_provider 包,但无论如何它都不起作用,而且我还希望具有网络兼容性。 Anyone know how to solve this?有谁知道如何解决这个问题? TY泰
When using shipped assets, you shouldn't use the host's file system.使用附带的资产时,不应使用主机的文件系统。 Instead use the rootBundle
from flutter/services
.而是使用flutter/services
的rootBundle
。
import 'package:flutter/services.dart';
...
Future<String> readFile(String lang) {
return rootBundle.loadString('text/$lang.toml');
}
Assuming the file is in a text/
directory at the root of your project and it is defined in the pubspec.yaml
:假设文件位于项目根目录的text/
目录中,并且它在pubspec.yaml
定义:
flutter:
assets:
- text/
The fact that it worked on Linux is kind of a coincidence, since you're running and developing on the same machine.它在 Linux 上运行的事实有点巧合,因为您在同一台机器上运行和开发。 This solution should work independent of which platform you're targeting.此解决方案应该独立于您的目标平台而工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.