Flutter. File existsSync() always returns false Flutter. File existsSync() always returns false dart dart

Flutter. File existsSync() always returns false


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