【问题标题】:Fetching pHp array or map as JSON data in Flutter?在 Flutter 中获取 pHp 数组或映射作为 JSON 数据?
【发布时间】:2020-09-23 05:37:47
【问题描述】:

我正在尝试在我的颤振应用程序中使用 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&lt;dynamic&gt;' is not a subtype of type 'List&lt;String&gt;'

服务器端代码(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;
?>

【问题讨论】:

    标签: php json flutter dart


    【解决方案1】:

    这是一个转换错误:List&lt;dynamic&gt; != List&lt;String&gt;

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

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

    json_serializable 将生成转换方法(fromJson 和 toJson)并处理一切。

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

    【讨论】:

    • 使用这个库获取useFriendList的代码是什么?
    • 这里的所有解决方案都很棒。但我最终使用了这个库。谢谢。
    【解决方案2】:

    正是错误所说的。 userFriendList 是 List 类型,您将其作为 List。

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

    应该是

    List<dynamic> userFriendList = []; 
    

    如果这不适合您,或者完全不同的列表。

    【讨论】:

    • 如果我以后打算将此列表中的项目用作字符串,例如在ListView 内的Text() 小部件中。在这种情况下我可以使用这个动态列表吗?
    • dynamic 是 Dart 处理未知类型的方式。您最初应该将它放在此列表中,然后将其解析为 List 稍后
    【解决方案3】:

    错误解释了它。从服务器 api 获取的数据被解码为 List&lt;dynamic&gt; 类型,并且您将 userFriendList 声明为 List&lt;String&gt; 类型。您需要做的是从

    更改 userFriendList 的类型
    List<String> userFriendList = ["No Friends"]; 
    

    到:

    List<dynamic> userFriendList = [];  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-02
      • 2020-07-09
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多