Как прочитать HTTP-запрос POST с типом возвращаемого класса в флаттере? - PullRequest
0 голосов
/ 08 сентября 2018

как я могу прочитать HTTP-ответ с типом возвращаемого класса?

мой класс

 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']

    );
  }
}

и мой HTTP-запрос

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]() Как я могу прочитать все данные и получаю каждый раз результат моментального снимка null.

1 Ответ

0 голосов
/ 08 сентября 2018

Ваш ответ содержит array of contact json. Поэтому вам, возможно, придется создать список контактов и вернуться, как показано ниже.

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

Тип возврата getDetails будет Future<List<ContactModal>>.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...