In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to read and write text files in Flutter". The editor shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to read and write text files in Flutter" can help you solve the problem.
Introduction
Text files (with .txt extension) are widely used to persist information, from digital data to long text. Today, I'll show you two examples of Flutter applications that use this file type.
The first example is quick and simple. It only uses rootBundle (from services.dart) to load content from the text in the assets folder (or another folder in the root project), and then outputs the results to the screen. This is useful when you only need to read data and not write data.
The second example is a little more complicated. It can not only read the content entered by the user, but also write the input by the user to a text file. You will learn how to use File asynchronous methods, including readAsString and writeAsString.
Example 1: load 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 contents will be loaded from the file.
Add a text file to your project
Create a new text file named data.txt in the asset folder of the project root (or one if it does not already exist) and add some virtual content to it, as follows:
Profile: Huawei Cloud expert, InfoQ contract author, Chief experience Officer of 51CTO blog, focusing on the sharing of front-end technologies, including Flutter, Mini Program, Android, VUE,JavaScript. If you are confused, take a look at the programmer's trajectory.
Don't forget to register the assets folder in the pubspec.yaml file:
Flutter: assets:-assets/ complete code
Add the following to your main.dart:
/ / main.dartimport '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, title:' nut', home: HomePage (),);}} class HomePage extends StatefulWidget {@ override _ HomePageState createState () = > _ HomePageState () } class _ HomePageState extends State {String _ data; / / This function is triggered when the user presses the floating button Future _ loadData () async {final _ loadedData = await rootBundle.loadString ('assets/data.txt'); setState (() {_ data = _ loadedData;}) } @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: Text ('nuts'),), 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),) Example 2: Reading and Writing gets the file path
For security reasons, Android and iOS do not 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 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 for Flutter).
Install the package by adding path_provider and its version to the dependencies section of the pubspec.yaml file, as follows:
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 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 do not need to manually create a text file and add it to the project. It is created automatically the first time the data is written.
This is the code in our main.dart:
/ main.dartimport '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, title:' nuts', home: HomePage (),) }} class HomePage extends StatefulWidget {@ override _ HomePageState createState () = > _ HomePageState ();} class _ HomePageState extends State {/ / This will be displayed on the screen String _ content; / / Find the Documents path Future _ getDirPath () async {final _ dir = await getApplicationDocumentsDirectory (); return _ dir.path;} / / This function is triggered when the "Read" button is pressed Future _ 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 _ 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),), 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,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,)],),) }} this is the end of the introduction to "how Flutter reads and writes text files". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.