簡體   English   中英

期望類型為“String”的值,但在 FutureBuilder SnapShot Flutter 中得到類型為“Null”的值

[英]Expected a value of type 'String', but got one of type 'Null' in FutureBuilder SnapShot Flutter

我是 FLutter 的新手,並嘗試獲取一些 JSON 數據並將其顯示在列表中。 當我嘗試連接到 API 時,它工作得很好,並且我從服務器獲得了 JSON 響應。 但是當我嘗試使用 FutureBuilder 在列表中顯示它時,它說快照返回 null,即使認為來自數據的響應是存在的。 這是我從服務器得到的 JSON 響應

{
            "error_code"     : "00",
            "error_message"  : "Success",
            "user_list"       : 
            [
                {
                    "name"   : "Swift",
                    "user_id": "2048"
                }, {
                    "name"   : "Python",
                    "user_id": "1024"
                }, {
                    "name"   : "Objective-C",
                    "user_id": "512"
                }, {
                    "name"   : "Ruby",
                    "user_id": "256"
                }
            ]
        }

這是我的get方法,因為我只想使用user_list字段,所以我嘗試這樣過濾。

Future<List<Patient>> getPatient() async {
    final response = await http.get(Uri.parse(url+"/interns"));
    if (response.statusCode == 200) {
        var data = json.decode(response.body);
        print(data['user_list']);
        return List<Patient>.from(data['user_list'].map((item)=>Patient.fromJson(item)));
    } else {
        throw Exception("Failed");
    }
  }

這是引發錯誤的 FutureBuilder

FutureBuilder<List<Patient>>(
                future: patientService.getPatient(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if(snapshot.hasError) {
                      print(snapshot);
                      return Center(
                        child: Text("Error"),
                      );
                  } else if (snapshot.hasData){
                      List<Patient> patients = snapshot.data;
                      return _buildListView(patients);
                  } else {
                      return Center(
                      child: Container(),
                    );
                  }
                },
              ),

這是患者模型類

Patient({required this.name, required this.userId});

    factory Patient.fromJson(Map<String, dynamic> json) {
      return Patient(
          name    :json['name'],
          userId  : json['userId']
      );
    }

這是我的錯誤

AsyncSnapshot<List<Patient>>(ConnectionState.done, null, Expected a value of type 'String', but got one of type 'Null'

它應該是

json['user_id ']而不是json['userId'] 參數名稱不同,這就是您收到 Null 錯誤的原因。

正如 John 在這篇文章中提到的,要修復您的代碼,您需要在解析Patient數據時使用user_id

但是,不確定您是否已經在代碼中修復了此問題,但是您共享的代碼最終會對端點進行許多額外調用,因為您正在 Build 方法中創建 Future getPatient 如果您在代碼中放置了斷點,則在第一次重新加載應用程序時應至少調用 3 次。

您應該將 Future 存儲在本地變量中並在FutureBuilder引用它。 這是我看到人們提出的一個非常常見的問題,我過去也遇到過這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM