这就是我现在面临的问题。
我有一个名为“assets”的文件夹,在该文件夹内有一个名为“no_icon.png”的图像。
我已将其添加到 pubspec.yaml 中,如下所示:
flutter:
assets:
- assets/teamShields/
- assets/no_icon.png
当我在 StatelessWidget 中执行操作时
final imageP = File('assets/no_icon.png');
然后在这个和一个 MaterialApp 里面:
body: Text(imageP.existsSync().toString()),
我总是在屏幕上看到错误。
另外,如果我输入Image.asset('assets/no_icon.png'),
我可以看到渲染的图像而不是文本。
我不知道这是一个错误还是我做错了什么......
您应该使用 Flutter 的资产支持,而不是使用文件。它旨在处理您在 pubspec 文件中声明的任何资产。
如果从有状态/无状态小部件使用,则看起来像这样:
Future<ByteData> loadFile(context) async {
AssetBundle bundle = DefaultAssetBundle.of(context).bundle;
try {
return await bundle.load("path/to.file");
} catch (e) {
print("Failed to load file because of $e");
return null;
}
}
你可以从任何有意义的地方调用它,即 initState 或使用 FutureBuilder。或者您可以使用:
import 'package:flutter/services.dart' show rootBundle;
...
Future<ByteData> loadAsset() async {
return await rootBundle.load('assets/some.file');
}
但是,您似乎正在尝试加载存在特殊情况的图像文件。
From the docs https://flutter.io/assets-and-images/:
Widget build(BuildContext context) {
// ...
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('graphics/background.png'),
// ...
),
// ...
),
);
// ...
}
您所需要做的就是使用 AssetImage =)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)