Why Can't I Load My Flutter Assets?
Some troubleshooting steps if you're running into issues loading assets in your Flutter app, either with
rootBundle.loadString() or something like
You haven't registered your assets
You get the following error message
Unable to load asset
Your asset hasn't been properly declared in your
pubspec.yaml file. This can either be due to not specifying the asset at all, or indenting incorrectly.
pubspec.yaml, and find the
flutter.assets section. You want to ensure that you are specifying each item under
assets as an array element (prefixed with a hyphen, indented).
- Whole folders can be specified by ensuring your item ends with a slash, however assets will only be pulled from that one level (i.e. asset declarations are not fully recursive).
- Further sub-directories can be used for image variants (such as dark equivalents, or relative sizes of images). See the Flutter documentation for more information on this.
- Pathing is relative to the root of the project, so if you put all of your assets in an
assets/directory, then every asset declaration must be prefixed with
flutter: assets: # Further indented by two spaces, with a hyphen at the start of each - assets/images/logo.png # A single file included - assets/images/splash/ # A directory containing several files
ServicesBinding.defaultBinaryMessenger was not initialized yet
You get the following unhandled exception:
E/flutter (12359): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value E/flutter (12359): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:222:39) E/flutter (12359): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:68:33) E/flutter (12359): #2 CachingAssetBundle.loadString.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:165:56) E/flutter (12359): #3 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:314:23) E/flutter (12359): #4 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:165:27)
The widget library hasn't yet been initialized. This can happen if you are trying to load an asset before your app has fully initialized.
Put the following code into your application. There's one import, then one line of code right before you need to run
// Import import 'package:flutter/widgets.dart' show WidgetsFlutterBinding; // Right before you would be doing any loading WidgetsFlutterBinding.ensureInitialized(); // Load the asset you wanted to load final configFile = await rootBundle.loadString('assets/env/development.json');