Make writing a habit together! This is the 9th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

This article is about reading and writing text files in Flutter.

introduce

Text files (with the.txt extension) are widely used to persist information, from digital data to long text. Today, I will introduce two sample Flutter applications that use this file type.

The first example is quick and simple. It simply loads content from text in the Assets folder (or another folder in the root project) using rootBundle (from services.dart), and then outputs the results to the screen. This is useful when you only need to read data without writing it.

The second example is a little more complicated. It can not only read user input, but also write user input to a text file. You’ll learn how to use File asynchronous methods, including readAsString and writeAsString.

Example 1: Loading content

preview

This example contains a text widget and a float button. When this button is pressed, the function _loadData is triggered and loads the content from the file.

Add a text file to your project

Create a new text file called data.txt in the assets folder of the project root (or if one doesn’t already exist) and add some virtual content to it, as follows:

Personal Profile: Huawei Cloud Sharing Expert, InfoQ contract writer, 51CTO blog CHIEF Experience Officer, focusing on front-end technology sharing, including Flutter, applets, Android, VUE, JavaScript. If you are confused, take a look at the path of the code farmer,Copy the code

Don’t forget to register the Assets folder in the pubspec.yaml file:

flutter:
  assets:
    - assets/
Copy the code

The complete code

Add the following to your main.dart:

// main.dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show rootBundle; import 'dart:async'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( DebugShowCheckedModeBanner: false, the title: 'nuts' home: HomePage ()); } } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String _data; // This function is triggered when the user presses the floating button Future<void> _loadData() async { final _loadedData = await rootBundle.loadString('assets/data.txt'); setState(() { _data = _loadedData; }); } @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (title: Text(' nut '),), body: Center( child: Container( width: 300, child: Text(_data ! = null ? _data : 'Nothing to show', style: TextStyle(fontSize: 24)))), floatingActionButton: FloatingActionButton(onPressed: _loadData, child: Icon(Icons.add)), ); }}Copy the code

Example 2: Reading and Writing

Obtaining the file path

For security reasons, Android and iOS don’t allow us to read or write anywhere on the hard drive. We need to save the text file to the Documents directory, where the application can only access its files. These files are deleted only when the application is deleted.

The file directory is NSDocumentDirectory for iOS and application data on Android. To get the full path to this directory, we use the **path_provider** package (this is the official package of Flutter).

Install the package by adding path_Provider and its version to the dependencies section of the pubspec.yaml file, as shown below:

Dependencies: path_provider: ^ mid-atlantic movedCopy the code

Then run the following command:

flutter pub get
Copy the code

And find the following path:

import 'package:path_provider/path_provider.dart'; / *... */ Future<String> get _getDirPath async { final _dir = await getApplicationDocumentsDirectory(); return _dir.path; }Copy the code

Sample preview

The sample application has a TextFiled that allows the user to enter his or her name to write to a text file. It also contains a text widget that shows the names read from the file.

Complete code and explanation

In this example, we do not need to manually create a text file and add it to the project. It is automatically created when data is written for the first time.

Here’s the code in our main.dart:

// main.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'dart:async'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( DebugShowCheckedModeBanner: false, the title: 'nuts' home: HomePage ()); } } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // This will be displayed on the screen String _content; // Find the Documents path Future<String> _getDirPath() async { final _dir = await getApplicationDocumentsDirectory(); return _dir.path; } // This function is triggered when the "Read" button is pressed Future<void> _readData() async { final _dirPath = await _getDirPath(); final _myFile = File('$_dirPath/data.txt'); final _data = await _myFile.readAsString(encoding: utf8); setState(() { _content = _data; }); } // TextField controller final _textController = TextEditingController(); // This function is triggered when the "Write" buttion is pressed Future<void> _writeData() async { final _dirPath = await _getDirPath(); final _myFile = File('$_dirPath/data.txt'); // If data.txt doesn't exist, it will be created automatically await _myFile.writeAsString(_textController.text); _textController.clear(); } @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (title: Text(' nut '),), body: Padding( padding: const EdgeInsets.all(20), child: Column( children: [ TextField( controller: _textController, decoration: InputDecoration(labelText: 'Enter your name'), ), ElevatedButton( child: Text('Save to file'), onPressed: _writeData, ), SizedBox( height: 150, ), Text( _content != null ? _content : 'Press the button to load your name', style: TextStyle(fontSize: 24, color: Colors.pink)), ElevatedButton( child: Text('Read my name from the file'), onPressed: _readData, ) ], ), ), ); }}Copy the code

conclusion

In this article, you built two simple applications and learned the basics of reading and writing text files. If you want to use JSON or CSV files in Flutter, check out the following article

\