在我的 Flutter API 中出現錯誤
顫振:型別“Null”不是型別轉換中“List”型別的子型別
當回應 json 串列為空時。我的 API 是用 Go 撰寫的。log.Println(mattersJSON)回傳[1111 2222 3333 4444]并fmt.Println(string(mattersJSON))回傳null。這是預期的,因為查詢不回傳任何記錄。
在 Flutter 中,我的 Api 中有以下代碼:
Future<List<Matter>> getMatters(BuildContext context) async {
List<Matter> matters = [];
try {
final response = await _helper.get(context, "/matters");
if (response.statusCode == 200) {
print(response.body);
if (response.body == null) {
return [];
}
print(response.body.length);
print('skipped test');
var parsed = json.decode(response.body) as List<dynamic>;
for (var matter in parsed) {
matters.add(Matter.fromJson(matter));
}
} else {
Navigator.pushNamed(context, RoutePaths.login);
return matters;
}
} catch (e) {
print(e);
return matters;
}
return matters;
}
輸出是這樣的:
顫振:空顫振:4顫振:跳過測驗顫振:型別'Null'不是型別轉換中型別'List'的子型別
我很想假設一個空的 response.body 串列的長度總是 4,而帶有記錄的 response.body 的長度總是大于 4。如果是這樣,那么我可以只測驗一個response.body.length > 4. 然而,這并不優雅,而且可能很脆弱。我擔心我看到的錯誤表明串列為空并print(response.body)回傳空,但 response.body 不為空。
如何正確測驗空回應串列并回傳 []?
uj5u.com熱心網友回復:
假設您在談論Responsefrom package:http, thenResponse.body是不可為空的,并且不能是null。
聽起來像是response.body文字字串'null'。如果您期待 JSON,那將是合理的。最終,您的問題是您正在執行無條件強制轉換( as List<dynamic>)。json.decode回傳一個dynamic型別而不是 aList或 aMap正是因為它可能回傳不同型別的物件,所以正確的解決方法是先檢查:
var parsed = json.decode(response.body);
if (parsed is List<dynamic>) {
for (var matter in parsed) {
matters.add(Matter.fromJson(matter));
}
}
然后您不需要明確檢查response.body是字串'null'還是json.decode回傳null.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453794.html
