将地图保存在本地并在其他地方使用

save map locally and use it elsewhere

我正在将地图转换为字符串,以便将其保存到设备内存中

_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');
        } 

现在我想将其用作地图以访问地图上的数据。有办法吗? 我的地图看起来像这样 {Everyone should read...: Harry Potter, Two truths and a lie...: something, I can quote every line from...: the alchemist}

你想要的是 JSON 文件。

JSON 是一种特殊语法,可用于在文件中存储地图和列表。

但有一个问题:您只能存储原始值的映射和列表,如字符串、整数或布尔值,自定义 class,例如,不能存储在 JSON 文件中。您必须先将其转换为地图。

为了将JSON 字符串转换为映射,您可以使用jsonDecode 函数。同样,jsonEncode 函数将 return 来自映射的字符串。

代码如下:

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);
}

在我的代码中,我跳过了 try-catch 块和目录,这只是为了让示例更简单。