问题
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
And when I do inside a StatelessWidget
final imageP = File('assets/no_icon.png');
and then inside this and a MaterialApp:
body: Text(imageP.existsSync().toString()),
I always see false on my screen.
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...
回答1:
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;
}
}
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');
}
However, it seems as though you're trying to load an image file for which there's a special case.
From the docs:
Widget build(BuildContext context) {
// ...
return DecoratedBox(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('graphics/background.png'),
// ...
),
// ...
),
);
// ...
}
All you need to do is use an AssetImage =).
来源:https://stackoverflow.com/questions/52653032/flutter-file-existssync-always-returns-false