[SOLVED] Use assets folder globally in flutter application


This Content is from Stack Overflow. Question asked by Giannis Petsis

i have a question,
I am developing an application using flutter, and inside the pubspec.yaml file i have included the assets directory. However, this directory only works on my PC. Say, when im opening a file i use the directory File("assets/data.txt"). But when run the application e.g. on my phone, it doesnt run the same way. Can anyone help me with that?

Thanks a lot


If you use File("assets/data.txt") inside your Flutter project, it actually tries to access the file in the assets folder inside your operating system. Your PC has this folder already, but your phone doesn’t because Flutter doesn’t create folders for assets.

Instead it creates an AssetBundle which contains every asset files you include in your pubspec.yaml. To access this bundle just:

import 'package:flutter/services.dart' show rootBundle;

and to access the specific text file:

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/data.txt');

If you deal with binary files, you call load(...) instead of loadString(...).


If you need this when the app starts, just call loadString(...) inside main(). For doing so, we need to ensure that the widget binding is already initialized:

void main() async {
  String text = await loadAsset());
  runApp(const MyApp());

This Question was asked in StackOverflow by Giannis Petsis and Answered by TripleNine It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?