在 Flutter 中获取 pHp 数组或地图作为 JSON 数据?

Gun*_*ack 5 php json dart flutter

我正在尝试在我的 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');
            }
}
Run Code Online (Sandbox Code Playgroud)

我明白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;
?>
Run Code Online (Sandbox Code Playgroud)

小智 3

这是一个强制转换错误:List<dynamic> != List<String>

您可以通过多种方式转换/投射您的列表。

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

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

这比手动操作更容易、更安全。