How to read and write a text file in Flutter

这一生的挚爱 提交于 2019-11-30 18:34:28

问题


How do you read text from a file and write text to a file?

I've been learning about how to read and write text to and from a file. I found another question about reading from assets, but that is not the same. I will add my answer below from what I learned from the documentation.


回答1:


Setup

Add the following plugin in pubspec.yaml:

dependencies:
  path_provider: ^0.4.1

Update the version number to whatever is current.

And import it in your code.

import 'package:path_provider/path_provider.dart';

You also have to import dart:io to use the File class.

import 'dart:io';

Writing to a text file

_write(String text) async {
  final directory = await getApplicationDocumentsDirectory();
  final file = File('${directory.path}/my_file.txt');
  await file.writeAsString(text);
}

Reading from a text file

Future<String> _read() async {
  String text;
  try {
    final directory = await getApplicationDocumentsDirectory();
    final file = File('${directory.path}/my_file.txt');
    text = await file.readAsString();
  } catch (e) {
    print("Couldn't read file");
  }
  return text;
}

Notes

  • You can also get the path string with join(directory.path, 'my_file.txt') but you need to import 'package:path/path.dart'.
  • Documentation


来源:https://stackoverflow.com/questions/54122850/how-to-read-and-write-a-text-file-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!