Flutter unable to load text from assets

1,122

Solution 1

I tried your code, and it works for me. Assets can be tricky. Sometimes you will need to restart the app completely after adding a new asset, or uninstall the app completely before running it again. You can also try running flutter clean.

An advice is to add if(snapshot.hasError) print(snapshot.error); before the else in the FutureBuilder just to see what the error is if it still does not work.

The reason you got an error about the null check when printing in main is because you need to add WidgetsFlutterBinding.ensureInitialized(); before using the root bundle to ensure that you have an instance of WidgetsBinding.

Solution 2

WidgetsFlutterBinding.ensureInitialized() was the key to solve my issue as well as @HannesHultergård wrote. To supplement his answer, the main should be:

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 print(await rootBundle.loadString("assets/test.txt"));
 runApp(MyApp());
}

Solution 3

You have to put your test.txt inside your assets folder in your project directory.

Also, it would be better if you could add your project directory structure to your post.

Instead of this,

flutter:
 uses-material-design: true
 assets:
  - assets/

Add this,

flutter:
 uses-material-design: true
 assets:
  - assets/test.text

Then run flutter pub get. It should be fine. Let us know if it worked.

Share:
1,122
bboett
Author by

bboett

Updated on December 29, 2022

Comments

  • bboett
    bboett over 1 year

    i have read https://flutter.dev/docs/development/ui/assets-and-images#asset-images-in-package-dependencies and Flutter - Read text file from assets and applied all there was but my code still doesn't work....

    i opened a new project for this, in the main folder i created assets and a file :

    pwd
     /home/bboett/AndroidStudioProjects/examen_companion
    bboett@hayate:~/AndroidStudioProjects/examen_companion$ ls -l assets/
     insgesamt 4
     -rw-r--r-- 1 bboett bboett 10 19. Mai 15:14 test.txt
     bboett@hayate:~/AndroidStudioProjects/examen_companion$ cat assets/test.txt 
      Hello!!
    

    then, not trusting android studio, i checked with vi, that in pubspec.yaml everything was ok:

    the file ends with:

    flutter:
     uses-material-design: true
     assets:
      - assets/
    

    i replaced the spaces, with 2 spaces before uses and assets: and 4 before - assets...

    in the _MyHomePageState class i changed :

      @override
      Widget build(BuildContext context)
      {
        AssetBundle bundle = DefaultAssetBundle.of(context);
        return FutureBuilder<String>(
            future: bundle.loadString("assets/test.txt"),
            builder: (context, AsyncSnapshot<String> snapshot)
            {
              if (snapshot.hasData) { return Text(snapshot.data.toString()); }
              else { return CircularProgressIndicator(); }
            }
      );
      }
    

    doesn't work.... i never come out of the progress indicator.... so directly in the main i added :

    void main() async {
     print(await rootBundle.loadString("assets/test.txt"));
     runApp(MyApp());
    }
    

    and that crashes with :

     Launching lib/main.dart on Linux in debug mode...
     Building Linux application...
     Debug service listening on ws://127.0.0.1:41355/L-ev6_eNIlI=/ws
     Syncing files to device Linux...
     [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used    on a null value
     #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:222:39)
     #1      AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:68:33)
     #2      CachingAssetBundle.loadString.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:165:56)
     #3      _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:311:23)
     #4      CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:165:27)
     #5      main (package:examen_companion/main.dart:9:26)
    

    i did after changing anything prior to the run a flutter clean.....

    version is :

     flutter upgrade
      Flutter is already up to date on channel beta
      Flutter 2.2.0-10.3.pre • channel beta • https://github.com/flutter/flutter.git
      Framework • revision 06e2fd6357 (vor 11 Tagen) • 2021-05-08 11:28:22 -0700
      Engine • revision a123e75c60
      Tools • Dart 2.13.0 (build 2.13.0-211.14.beta)
    

    flutter doctor run ok too, oh and i have the same error on linux or android, so its not the device....

    so i am pretty clueless on how to get this work, since i have the impression to have followed documentation and previous help :(

    BTW i thought that flutter was now null, safe... anyway, how do i get this to work?

    thanks in advance

    [edit]: even stranger.... i replaced

        //future: bundle.loadString("assets/test.txt"),
        future: bundle.loadString('AssetManifest.json'),
    

    and got :

     flutter: {"assets/test.txt":["assets/test.txt"],"packages/cupertino_icons/assets/CupertinoIcons.ttf":["packages/cupertino_icons/assets/CupertinoIcons.ttf"]}
    

    so the file is there??? why can't i open/get it??

    [ed2]: ok, i don't get it..... i tryed this directly in main:

     print(await rootBundle.loadString('AssetManifest.json'));
    

    and that crashed too with the null exception....

  • bboett
    bboett almost 3 years
    that did it... but i don't understand? in flutter.dev/docs/development/ui/… its written, that if you postpend the asset name with a / the whole directory will be included? and by loading the AssetManifest.json the file showed?? strange stuff...
  • bboett
    bboett almost 3 years
    yes but there's a timer on accepting the answer ;)
  • Ratnadeep
    Ratnadeep almost 3 years
    Great to know. If it solved then mark it as solved. Cheers mate!
  • Hannes Hultergård
    Hannes Hultergård almost 3 years
    I'm not sure if this should be the accepted answer. The documentation explicitly states that all files in the directory is included if you end the path with /, and I know from experience that it works with images and fonts at least. If there is a reason that that does not work in that case you should provide an explanation in your answer.
  • bboett
    bboett almost 3 years
    oh... and BTW in my post there was the file structure? pretty much at the start of the post.... and i am still annoyed by the fact that i will now have to add every single file in the assets to the pubspec.... oh well...
  • bboett
    bboett almost 3 years
    @HannesHultergård so my thing should have worked? then why didn't it? i would very much prefer a wildcard solution....
  • Hannes Hultergård
    Hannes Hultergård almost 3 years
    It should as far as I can tell; I'm still trying to figure out why it doesn't...
  • Ratnadeep
    Ratnadeep almost 3 years
    @bboett ... my apologies, I should have gone through the doc thoroughly. Now I am checking it out. So, please unmark the answer for the benefit of the community.
  • bboett
    bboett almost 3 years
    i did tons of flutter clean :D but yeah! good pointer for the ensureInitialized... overlooked that one.. and yeah... WTF.... now removing the file names in the pubspec work too :( i would have preferred a clean error..... (would have spared me a day of frustration :D) hmmm about uninstalling : that's why i started to switch back and forth between linux app and android app, but indeed i didn't try to uninstall the app beforehand...
  • Hannes Hultergård
    Hannes Hultergård almost 3 years
    Yeah, that has confused me a few times as well. Flutter clean usually works when you have weird behavior. Glad you got it sorted
  • Senthur Kumaran
    Senthur Kumaran over 2 years
    This one worked for me.
  • Senthur Kumaran
    Senthur Kumaran over 2 years
    Can you check this question as well? How to read XML files in flutter?