Flutter. File existsSync() always returns false

5,688

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 =).

Share:
5,688
Isaac
Author by

Isaac

Updated on December 07, 2022

Comments

  • Isaac
    Isaac over 1 year

    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...

  • Isaac
    Isaac over 5 years
    Yes, but I'm trying to prevent my program to try to load an assets that doesn' exists. Do you know how to do that?
  • rmtmckenzie
    rmtmckenzie over 5 years
    That's not really what assets are meant for.... you need to predefine exactly which assets get included in the build and therefore your app should never try to load one that doesn't exist (and it does, that's a bug). But the way to do that is exactly what I described in the first part of the answer, using a try & catch around loadFile. I don't think there's a synchronous way of doing that though, if that's what you're trying to do.
  • Isaac
    Isaac over 5 years
    Doesn't have to be syncronous, but trying the first part of your answer it throws an error, it's like it is ignoring the try catch part. I also have tried using catchError and still the same