亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Flutter 中獲取 pHp 數組或地圖作為 JSON 數據?

在 Flutter 中獲取 pHp 數組或地圖作為 JSON 數據?

PHP
蕭十郎 2023-04-28 16:35:44
我正在嘗試在我的 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;?>
查看完整描述

3 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

這是一個轉換錯誤:List<dynamic> != List<String>

您可以通過多種方式轉換/投射您的列表。

我建議你使用這個庫來簡化你的 json / Dart 對象轉

json_serializable 將生成轉換方法(fromJson 和 toJson)并處理所有事情。

它比手動操作更容易、更安全。


查看完整回答
反對 回復 2023-04-28
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

錯誤解釋了它。從服務器 api 獲取的數據被解碼為 typeList<dynamic>并且您將 userFriendList 聲明為 type List<String>。您需要做的是將 userFriendList 的類型從

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

到:

List<dynamic> userFriendList = [];


查看完整回答
反對 回復 2023-04-28
?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

正是錯誤所說的。userFriendList 是 List 類型,您將其作為 List。

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

應該

List<dynamic> userFriendList = [];

如果這對您不起作用,或者完全不同的列表。


查看完整回答
反對 回復 2023-04-28
  • 3 回答
  • 0 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號