這是 dart 中的完整控制臺應用程式。它不顫抖。我需要從本地 json 檔案匯入資料并將其作為回應發送。我需要將資料作為 dart 中的 Map 陣列讀取。資料格式如下。
{
"users":[
{
"id":1,
"user":"user1",
"password":"p455w0rd"
},
{
"id":2,
"user":"user2",
"pass":"p455w0rd"
}
]
}
在我看到 Flutter 示例的每個地方,它都將 Flutter/services 作為 rootBundle 匯入以讀入 JSON 檔案。我沒有找到在純飛鏢中實作這一點的方法。
uj5u.com熱心網友回復:
使用dart:io和dart:convert。
下面的簡單例子。如果檔案不存在或格式錯誤,請記住添加例外處理。
import 'dart:convert';
import 'dart:io';
Future<List<Map>> readJsonFile(String filePath) async {
var input = await File(filePath).readAsString();
var map = jsonDecode(input);
return map['users'];
}
uj5u.com熱心網友回復:
首次匯入dart:convert.
您可以按如下方式決議 JSON 檔案中的資料:
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449853.html
