6

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
  • 1,436
  • 2
  • 15
  • 29

1 Answers1

2

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

rmtmckenzie
  • 37,718
  • 9
  • 112
  • 99
  • 1
    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? – Isaac Oct 05 '18 at 22:27
  • 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. – rmtmckenzie Oct 05 '18 at 22:35
  • 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 – Isaac Oct 05 '18 at 23:49