在Flutter中将PHP数组或映射作为JSON数据获取?

5

我正在尝试在我的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;
?>
3个回答

3

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

您可以通过多种方式将列表进行转换/强制转换。

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

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

相比手动处理,它更加容易和安全。


使用这个库,获取 useFriendList 的代码将是什么? - GunJack
1
这里提供的所有解决方案都很棒。但是我最终使用了这个库。谢谢。 - GunJack

1

错误提示很清楚,userFriendList是List类型,但你将其定义为List。

List<String> userFriendList = ["No Friends"]; 

应该是


List<dynamic> userFriendList = []; 

如果这不适合您,也可以选择完全不同的列表。

如果我以后打算将此列表的项目用作字符串,例如在ListView内部的Text()小部件中。那么我能在这种情况下使用这个动态列表吗? - GunJack
动态类型是Dart处理未知类型的方式。您应该最初将其放入此列表中,然后将其解析为List<String>。 - returnVoid

1
错误信息已经解释了问题所在。从服务器API获取的数据被解码成类型 List<dynamic>,而你声明了userFriendList的类型为List<String>。你需要做的是将userFriendList的类型更改为
List<String> userFriendList = ["No Friends"]; 

至:

List<dynamic> userFriendList = [];  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接