代码之家  ›  专栏  ›  技术社区  ›  sekhar

如何在flatter中读取带有类返回类型的HTTP POST请求?

  •  0
  • sekhar  · 技术社区  · 6 年前

    如何读取具有类返回类型的HTTP post响应?

    我的班级是

     class ContactModal {
    
      String code;
      String status;
      String name;
    
      ContactModal({this.code, this.status, this.name});
    
      factory ContactModal.fromJson(Map<String, dynamic> json) {
        return ContactModal(
            code: json['code'],
            status: json['status'],
            name: json['name']
    
        );
      }
    }
    

    class ApiClient {
          Future<ContactModal> getDetails(String token) async {
    
            print("inside get file "+token);
            var response = await http
                .get(Uri.parse(this.apiBaseUrl + "/file-list/"), headers: {
              "Accept": "application/json",
              "Authorization":  token
            });
    
            if (response.statusCode == 200) {
              print("Json response"+response.body);
              return ContactModal.fromJson(json.jsonDecode(response.body));
            } else {
              print("Json exception response");
              throw Exception('Failed to fetch access token');
            }
    }
          }
    

    我的建筑工人是

         body: new Container(
              child: new FutureBuilder(
                future: apiClient.getFileDetails(this.accessToken),
                builder: (context, snapshot) {
                  print(" prefs.getString('accessTokenValue') "+snapshot.data);
                 if (snapshot.hasData) {
                    print("Snap shot data : "+snapshot.data);
                    new ContactsList(_buildContactList(snapshot));
    
                  } else if (snapshot.hasError) {
                    return new Text("${snapshot.error}");
                  }
    // By default, show a loading spinner
                  return new CircularProgressIndicator();
                },
              ),
            ),
    

    我的api将返回响应 List[ContactModal]() 我怎样才能读取所有数据并每次都获取数据

    1 回复  |  直到 6 年前
        1
  •  0
  •   Dinesh Balasubramanian    6 年前

    您的答复包含 array of contact json

     var jsonArray = json.jsonDecode(response.body);
    var contactList = jsonArray.map((json) => ContactModal.fromJson(json)).toList();
    

    getDetails的返回类型将为 Future<List<ContactModal>> .