Press "Enter" to skip to content

Flutter : Read Text File from Assets

On previous tutorial, we learnt how to read json file from Server. In this tutorial, we can learn how to read content of a text (txt) from assets in Flutter.

1. Set up Text File

First of all, created a folder to keep the file named ‘assets’ on flutter project directory. (You can give any name instead).

Then creates a new file named ‘mytextfile.txt’.

Just inserted some text inside the file.

2. Add the file as assets on pubspec.yaml file

  assets:
    - assets/mydata.txt
Adding assets to pubspec yaml file

3. Import services.dart package on project file

import 'package:flutter/services.dart';

4. Read Text File

String dataFromFile = "";
Future<void> readText() async {
  final String response = await rootBundle.loadString('assets/mydata.txt');
  setState(() {
    dataFromFile = response;
  });
}

5. Display the Content

Container(
  child: Text(dataFromFile),
);

Full Code:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Read Text File';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ReadTextFile(),
      ),
    );
  }
}
class ReadTextFile extends StatefulWidget {
  const ReadTextFile({Key? key}) : super(key: key);

  @override
  _ReadTextFileState createState() => _ReadTextFileState();
}

class _ReadTextFileState extends State<ReadTextFile> {
  String dataFromFile = "";

  Future<void> readText() async {
    final String response = await rootBundle.loadString('assets/mydata.txt');
    setState(() {
      dataFromFile = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    readText();
    return Container(
      child: Text(dataFromFile),
    );
  }
}

Sample Output:

Flutter: Read Text File from Assets

If you want to read a json file from assets and fetch it’s content as list items, then read this article.

Be First to Comment

Leave a Reply