简体   繁体   中英

What is the best way to work with files in Flutter?

I'm a junior working with flutter and hit a problem. I need to open a file, read and compare some data everytime the app opens and then change some of that data as the app progress. We tried using.txt files to read and write some text, but when we had to look for something in the file was too complicated to change it and the file is not accessibe only on the device running the app. We also thought of using xml files but I don't know if is a good idea. What would be a pratical solution for this situation, as the file needs to be opened all the time. Thanks.

Let's say our JSON looks like this:

{
  title: 'some text',
  values: [1,5,2,4,1,3],
}

And we want to make a UI that allows us to add values and to edit the title. First let's write a method to write and read from the JSON file:

Future<void> _write(Map<String, dynamic> value) async {
  File f = File(_fileLocation);

  String jsonStr = jsonEncode(value);

  await f.writeAsString(jsonStr);
}

Future<Map<String, dynamic>> _read() async {
  File f = File(_fileLocation); // maybe move this into a getter

  final jsonStr = await f.readAsString();

  return jsonDecode(jsonStr) as Map<String, dynamic>;
}

This way, the rest of the app should be trivial, but let's add a method to update the title and a method to add a new number:

Future<void> _updateTitle(String title) async {
  var values = await _read();
  values['title'] = title;
  await _write(values);
}

Future<void> _addNumber(int number) async {
  var values = await _read();
  values['values'].push(number);
  await _write(values);
}

Types with JSON and Dart can be a bit weird, so it is possible you need to use the as keyword when reading from the list:

Future<void> _addNumber(int number) async {
  var values = await _read();

  var valueList = (values['values'] as List<int>);
  valueList.push(number);
  values['values'] = valueList;

  await _write(values);
}

Hopefully, this example helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM