问题描述
这是我现在面临的问题。
我有一个名为 assets的文件夹,并且在该文件夹中有一个名为 no_icon.png的图像。
我已将其添加到pubspec.yaml中,如下所示:
this is the problem that I'm facing right now.I have a folder named 'assets' and inside that folder I have an image named 'no_icon.png'.I have added this to the pubspec.yaml like this:
flutter:
assets:
- assets/teamShields/
- assets/no_icon.png
当我这样做时在StatelessWidget中
And when I do inside a StatelessWidget
final imageP = File('assets/no_icon.png');
,然后在其中添加一个MaterialApp:
and then inside this and a MaterialApp:
body: Text(imageP.existsSync().toString()),
我总是在屏幕上看到错误。
I always see false on my screen.
此外,如果我键入 Image.asset('assets / no_icon.png' ),
而不是文本,我可以看到渲染的图像。
Also, if I type Image.asset('assets/no_icon.png'),
instead of Text I can see the image rendered.
我不知道这是错误还是我做错了...
I don't know if this is a bug or it's something I'm doing wrong...
推荐答案
与其使用文件,不应该使用Flutter的资产支持。它旨在处理您在pubspec文件中声明的所有资产。
Rather than using files you should be using Flutter's asset support. It's designed to handle any assets you've declared in your pubspec file.
如果从有状态/无状态窗口小部件中使用,它将看起来像这样:
That would look something like this if used from a stateful/stateless widget:
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。或者,您可以使用:
And you'd call that from wherever makes sense i.e. initState or with a FutureBuilder. Or you can use:
import 'package:flutter/services.dart' show rootBundle;
...
Future<ByteData> loadAsset() async {
return await rootBundle.load('assets/some.file');
}
但是,似乎您要加载的是特殊情况的图像文件。
来自:
Widget build(BuildContext context) {
// ...
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('graphics/background.png'),
// ...
),
// ...
),
);
// ...
}
所有您需要做的就是使用一个AssetImage =)。
All you need to do is use an AssetImage =).
这篇关于扑。文件existSync()始终返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!