introduce
Text files (with the .txt extension) are widely used to persist in storing information, from digital data to long text. Today, I will introduce 2 examples of Flutter applications using this file type.
The first example is quick and simple. It only loads the content from the text in the assets folder (or another folder in the root project) using rootBundle (from ) and then outputs the result 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 the content entered by the user, but also write the content entered by the user to a text file. You will learn how to use File asynchronous methods, including readAsString and writeAsString.
Example 1: Loading content
Preview
This example contains a text widget and a floating button. When this button is pressed, the function _loadData will be triggered and the content will be loaded from the file.
Add text files to your project
Create a new text file named (if it does not exist yet) in the asset folder in the project root directory and add some dummy content to it as follows:
Personal Profile:Huawei Cloud Enjoy Expert,InfoQSigned Author,51CTOChief Experience Officer of Blog,Focus on sharing of front-end technology,includeFlutter,Mini Program,Android,VUE,JavaScript。If you're confused,Why not take a look at the coder's track,
Don't forget to be hereRegister in the fileassetsFolder:
flutter: assets: - assets/
Complete code
Add the following to your:
// import 'package:flutter/'; import 'package:flutter/' show rootBundle; import 'dart:async'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'nut', 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 ('assets/'); 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()), ); } }
Example 2: Reading and Writing
Get file path
Android and iOS do not allow us to read and write anywhere on our hard drive for security reasons. We need to save the text file toDocumentsIn a directory, an application can only access its files in that directory. These files are deleted only when you delete the application.
ShoulddocumentThe directory isNSDocumentDirectoryiOS andApplication DataOn Android. To get the full path to the directory, we usepath_providerPackage (this is the official package of Flutter).
Bypath_providerand its version added toFiledDependenciesPartially install the package, as shown below:
dependencies: path_provider: ^2.0.8
Then run the following command:
flutter pub get
And find the following path:
import 'package:path_provider/path_provider.dart'; /* .... */ Future<String> get _getDirPath async { final _dir = await getApplicationDocumentsDirectory(); return _dir.path; }
Sample Preview
This sample application has a TextFiled that allows the user to enter his/her name to write to a text file. It also contains a text widget that displays the name read from the file.
Complete code and explanation
In this example, we don't need to manually create the text file and add it to the project. It will be created automatically when the data is first written.
This is oursmiddleCode:
// import 'dart:convert'; import 'package:flutter/'; 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, title: 'nut', 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/'); 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/'); // If 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 (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: )), ElevatedButton( child: Text('Read my name from the file'), onPressed: _readData, ) ], ), ), ); } }
The above is a detailed explanation of how Flutter reads and writes text files. For more information about Flutter reading and writing text files, please pay attention to my other related articles!