Giannis Petsis
Giannis Petsis

Reputation: 59

Use assets folder globally in Flutter application

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 I'm opening a file I use the directory File("assets/data.txt"). But when I run the application, e.g., on my phone, it doesn't run the same way. How can I do that?

The pubspec.yaml file:

name: example
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

Upvotes: 2

Views: 2037

Answers (1)

TripleNine
TripleNine

Reputation: 1932

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

Upvotes: 2

Related Questions