[英]How can I convert a `List<Map<String,String>>` to a `Set<Map<String,String>>` in flutter?
[英]How do i convert a String to a List<Map<String,String>>
我有一個包含多個鍵和值的列表,然后將它們映射到要顯示的 DataTable 中。
List<Map<String, String>> listOfColumns = [
{"Name": "John", "Number": "1", "State": " "},
{"Name": "Brad", "Number": "2", "State": " "},
{"Name": "Ryan", "Number": "3", "State": " "},
{"Name": "Grant", "Number": "4", "State": " "},
];
現在,我想要保存數據表中的數據。 所以我簡單地使用了文件 IO 系統,我創建了一個名為 _save() 和 _read() 的異步函數,在 _save() 中我將 listOfColumns 轉換為字符串。
_read() async {
try {
final directory = await getExternalStorageDirectory();
final file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
}
_save() async {
final directory = await getExternalStorageDirectory();
final file = File('${directory.path}/my_file.txt');
final List<Map<String, String>> data = listOfColumns;
await file.writeAsString(data.toString());
print('saved');
}
現在,當談到從文件中讀取數據時,事情就是這樣 - 我實際上如何將變量文本轉換回List<Map<String,String>>
? 我完全不知道如何實現這一目標。 任何幫助都受到高度贊賞。 謝謝。
您應該首先將其保存為JSON (使用jsonEncode
,然后您可以輕松地將其轉換回來:
Future<void> _save() async {
...
final jsonString = jsonEncode(listOfColumns);
await file.writeAsString(jsonString);
}
現在,您可以使用jsonDecode
輕松加載數據:
Future<void> _read() async {
...
final decoded = jsonDecode(await file.readAsString()) as List;
listOfColumns = decoded.cast<Map<String, dynamic>>()
.map((map) => map.cast<String, String>()).toList();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.