Home > Enterprise >  Use assets folder globally in flutter application
Use assets folder globally in flutter application

Time:09-19

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

Edit: pubspec.yaml file:

description: A new Flutter project.


publish_to: 'none'


version: 1.0.0 1

environment:
  sdk: ">=2.17.6 <3.0.0"


dependencies:
  intl: ^0.17.0
  
  flutter:
    sdk: flutter

  path_provider: ^1.6.27

  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^2.0.0


flutter:

  uses-material-design: true

  assets:
    - assets/logo.png
    - assets/states.txt
    - assets/states1.txt```

CodePudding user response:

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

EDIT:

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 {
  WidgetsFlutterBinding.ensureInitialized(); // 
  String text = await loadAsset());
  runApp(const MyApp());
}
  • Related