How to Read Text File From Assets In Flutter ?

· 3 min read
Read Text File From Assets In Flutter
Read Text File From Assets In Flutter

Earlier we have been through how to access SVG Picture in Flutter. So now in this tutorial, we will walk through How to Read Text File From Assets In Flutter?

How to Read Text File From Assets In Flutter?

Kindly follow the below Steps to Read Text File From Assets In Flutter.

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.
Assets in Flutter
Assets in Flutter

 

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.

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 at the root of your project. Add an asset 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.
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');
}

Conclusion:

In this article, we have learned about How to Read Text File From Assets In Flutter?

Thanks for being with us !!!
Keep Learning.

Do let us know if you need any assistance with Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply