我试图在我的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');
            }
}

我正确地获得了usrLvluserName。但是对于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;
?>

最佳答案

这是强制转换错误:List<dynamic> != List<String>
您可以通过多种方式转换/投放列表。

我建议您使用此库来简化json / Dart对象转换
:https://pub.dev/packages/json_serializable

json_serializable将生成转换方法(fromJson和toJson)并处理所有事情。

比手动进行操作更简单,更安全。

关于php - 在Flutter中获取pHp数组或映射为JSON数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62191188/

10-10 18:04
查看更多