Flutter - Read text file from assets
I have a text file (.txt) that I'd like to be an asset that I can scan in later.
In the pubspec.yaml, I've made sure that:
flutter:
assets:
- res/my_file.txt
exists. The file resides in the res/
folder that I made, on the same level as lib/android/
and ios/
I'm trying to read the file from a custom class, not a widget.
According to the documentation, I'm to use this import:
import 'package:flutter/services.dart' show rootBundle;
and start reading like so:
/// Assumes the given path is a text-file-asset.
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
And to get the actual data, do:
String data = await getFileData(fileName);
However, when I use a fileName
like 'assets/res/my_file.txt'
, I get an error: Unable to load asset: assets/res/my_file.txt
.
It's also worth noting that I'm trying to do this from a unit test. Any ideas on how to properly do this? Thanks!
Here is a fuller answer for future visitors.
Create an assets folder
Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory.
You can create another subfolder for text files in assets
if you like. But if you do, you have to include the relative path in pubspec.yaml. See below.
Add your text file to the new folder
You can just copy your text file into the assets
directory. The relative path of my_file.txt
, for example, would be assets/my_file.txt
.
Register the assets folder in pubspec.yaml
Open the pubspec.yaml file that is in the root of your project.
Add an assets subsection to the flutter section like this:
flutter:
assets:
- assets/my_file.txt
If you have multiple files that you want to include, then you can leave off the file name and just use the directory name (include the final /):
flutter:
assets:
- assets/
Get the text in code
You can use the global rootBundle
to get the text file asset:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}
Or if you have the BuildContext (inside a widget) you can use DefaultAssetBundle. This is recommended because it allows switching asset bundles at runtime, which is useful for multilingual assets.
Future<String> loadAsset(BuildContext context) async {
return await DefaultAssetBundle.of(context).loadString('assets/my_text.txt');
}
See also
- Loading text assets
- How to include images in your app
The folder name "assets" isn't magically added. Update your pubspec.yaml
to include the full path to the asset.
flutter:
assets:
- assets/res/my_file.txt