我正在尝试在我的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;
?>
useFriendList
的代码将是什么? - GunJack