我正在嘗試在我的 flutter 應用程序中使用 json 從服務器獲取一些數據。這是我正在使用的功能。List<String> userFriendList = ["No Friends"]; Future<http.Response> _fetchSampleData() { return http.get('//link/to/server/fetcher/test_fetcher.php');}Future<void> getDataFromServer() async { final response = await _fetchSampleData(); if (response.statusCode == 200) { Map<String, dynamic> data = json.decode(response.body); userLvl = data["lvl"].toString(); userName = data["name"]; userFriendList = List(); userFriendList = data["friendlist"]; } else { // If the server did not return a 200 OK response, // then throw an exception. print('Failed to load data from server'); }}我明白usrLvl了userName。但是對于userFriendList,我收到以下錯誤:[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'服務器端代碼(test_fetcher.php):<?php $myObj->name = "JohnDoe"; $myObj->lvl = 24; $friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes"); $myObj->friendlist = $friends; header('Content-Type: application/json'); $myJSON = json_encode($myObj); echo $myJSON;?>
3 回答

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
這是一個轉換錯誤:List<dynamic> != List<String>
您可以通過多種方式轉換/投射您的列表。
我建議你使用這個庫來簡化你的 json / Dart 對象轉
json_serializable 將生成轉換方法(fromJson 和 toJson)并處理所有事情。
它比手動操作更容易、更安全。

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
錯誤解釋了它。從服務器 api 獲取的數據被解碼為 typeList<dynamic>
并且您將 userFriendList 聲明為 type List<String>
。您需要做的是將 userFriendList 的類型從
List<String> userFriendList = ["No Friends"];
到:
List<dynamic> userFriendList = [];

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
正是錯誤所說的。userFriendList 是 List 類型,您將其作為 List。
List<String> userFriendList = ["No Friends"];
應該
List<dynamic> userFriendList = [];
如果這對您不起作用,或者完全不同的列表。
- 3 回答
- 0 關注
- 178 瀏覽
添加回答
舉報
0/150
提交
取消