【发布时间】:2022-01-21 11:37:59
【问题描述】:
我遵循了颤振文档中的指南,但不明白它是如何工作的。
我有一个包含用户信息的现有文件,我希望能够写入/更新该文件。
这是我的代码的相关部分:
Future<bool> sendMessage(String sender, String target, String body) async {
String tempAccountData = await loadMessage();
List<Map<String, dynamic>> accountData =
List<Map<String, dynamic>>.from(jsonDecode(tempAccountData));
//find valid target
print(accountData);
print(target);
for (Map<String, dynamic> accountInfo in accountData) {
if (accountInfo["username"] == target) {
//write message
accountInfo["messages"]
.add({"time": DateTime.now(), "sender": sender, "message": body});
writeMessage(accountData);
return true;
}
}
return false;
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print(path);
return File('$path/accountInfo.json');
}
Future<File> writeMessage(List<Map<String, dynamic>> accountData) async {
File file = await _localFile;
// Write the file
return file.writeAsString('$accountData');
}
我不知道路径是什么,我将文件放入 assets/data 中,如下面的屏幕截图所示:(我正在尝试从 accountInfo.dart 读取/写入 accountInfo.json)
【问题讨论】: