Flutter. File existsSync() always returns false

旧时模样 提交于 2019-12-11 07:05:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!