Home > database >  save map locally and use it elsewhere
save map locally and use it elsewhere

Time:02-26

I'm converting a map to a string in order to save it to the device memory

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

        _save() async {
          final directory = await getApplicationDocumentsDirectory();
          final file = File('${directory.path}/answers.txt');
          await file.writeAsString(answers.toString());
          print('saved');
        } 

now I want to use it as a map to access the data on the map. is there a way to do it? my map looks like this {Everyone should read...: Harry Potter, Two truths and a lie...: something, I can quote every line from...: the alchemist}

CodePudding user response:

What you want is a JSON file.

JSON is a special syntax that can be used to store maps and lists in a file.

There is a catch though: You may only store maps and lists of primitive values like string, int or bool, a custom class, for example, cannot be stored in a JSON file. You would have to convert it into a map first.

In order to turn a JSON string into a map, you can use the jsonDecode function. Similarly, the jsonEncode function will return a string from a map.

Here goes the code:

Future<Map<String, dynamic>> _read() async {
  final file = File(filePath);
  final jsonStr = await file.readAsString()

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

Future<void> _write(Map<String, dynamic> map) async {
  final jsonStr = jsonEncode(map);

  final file = File(filePath);

  await file.writeAsString(jsonStr);
}

In my code I skipped the try-catch block and the Directory thing, that's just to make the example simpler.

  • Related