![](/img/trans.png)
[英]Problem with [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
[英]ERROR:flutter/runtime/dart_vm_initializer.cc(41) Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index' for json file ,flutter
我正在嘗試從 JSON 文件中獲取兩個 int
這是 api 響應
[
{
"New_V": 30,
"Old_V": 29
}
]
當我使用 jsonDecode 獲取這兩個 int 時,標記代碼中出現錯誤
我不斷得到
未處理的異常:類型“String”不是“index”的“int”類型的子類型
在代碼行
newV = vData['New_V'].toInt();
這是我的代碼
isTheirUpdate() async {
var vData;
try {
Response response =
await get(Uri.parse('https://0000000000000/check_v.json'));
if (response.statusCode == 200) {
vData = jsonDecode(response.body);
print(vData);
int newV;
int oldV;
setState(() {
newV = vData['New_V'].toInt(); /////////// I get error here "type 'String' is not a subtype of type 'int' of 'index'"
oldV = vData['Old_V'].toInt();
});
if (newV == KCheckAppVersion) {
isTheirInternet;
} else if (oldV == KCheckAppVersion) {
showDialog()
} else {
showDialog()
}
}
} on SocketException catch (_) {}
}
我想念一些東西,但我不知道它是什么有人可以解釋這行代碼的原因和修復方法嗎?
謝謝
你的變量是string
,你不能在string
上使用toInt()
,嘗試用這種方式解析為int
:
newV = int.parse(vData['New_V'].toString());
oldV = int.parse(vData['Old_V'].toString());
看起來問題出在 vData 變量的類型上。 看起來 vData 變量被設置為 jsonDecode 的結果,它將返回一個包含 JSON 數據的 Map<String, dynamic>。 但是,代碼嘗試使用字符串鍵(如 vData['New_V'])訪問 vData map 中的元素,就好像它是一個列表一樣。
要解決此問題,您可以嘗試將設置 vData 變量的代碼行更改為:
vData = jsonDecode(response.body) as Map<String, dynamic>;
這會將 jsonDecode 的結果顯式轉換為正確的類型,即 Map<String, dynamic>。 然后,您可以使用正確的語法訪問 map 中的值,例如 vData['New_V']。
例如,以下代碼應該可以工作:
setState(() {
newV = vData['New_V'];
oldV = vData['Old_V'];
});
我希望這有幫助。 如果您有任何問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.