Android Studio Flutter快照.hasData为假,但响应有数据

v2g6jxz6  于 2023-01-02  发布在  Android
关注(0)|答案(1)|浏览(121)

我有这个Flutter项目,有主屏幕。我已经发送http获取请求到API的URL,我需要从快照获取数据。但snapShot.hasData返回假。
打印响应正文时的控制台输出。

Performing hot reload...
Syncing files to device sdk gphone64 x86 64...
I/flutter ( 4384): NoSuchMethodError: Class 'MappedListIterable<Map<String, dynamic>, User>' has no instance method 'tolist'.
I/flutter ( 4384): Receiver: Instance of 'MappedListIterable<Map<String, dynamic>, User>'
I/flutter ( 4384): Tried calling: tolist()
Reloaded 1 of 671 libraries in 1,336ms (compile: 141 ms, reload: 534 ms, reassemble: 567 ms).
D/EGL_emulation( 4384): app_time_stats: avg=271975.19ms min=271975.19ms max=271975.19ms count=1
I/flutter ( 4384): [{"name":"James Calton","city":"London","image":"https://randomuser.me/api/portraits/men/78.jpg"},{"name":"Don Quixote","city":"Madrid","image":"https://randomuser.me/api/portraits/men/74.jpg"},{"name":"Joan of Arc","city":"Paris","image":"https://randomuser.me/api/portraits/men/76.jpg"},{"name":"Rosa Park","city":"Alabama","image":"https://randomuser.me/api/portraits/men/75.jpg"},{"name":"James Calton","city":"London","image":"https://randomuser.me/api/portraits/men/78.jpg"},{"name":"Don Quixote","city":"Madrid","image":"https://randomuser.me/api/portraits/men/74.jpg"},{"name":"James Calton","city":"London","image":"https://randomuser.me/api/portraits/men/78.jpg"},{"name":"Don Quixote","city":"Madrid","image":"https://randomuser.me/api/portraits/men/74.jpg"},{"name":"James Calton","city":"London","image":"https://randomuser.me/api/portraits/men/78.jpg"},{"name":"Don Quixote","city":"Madrid","image":"https://randomuser.me/api/portraits/men/79.jpg"},{"name":"James Calton","city":"London","image":"https://rand
I/flutter ( 4384): NoSuchMethodError: Class 'MappedListIterable<Map<String, dynamic>, User>' has no instance method 'tolist'.
I/flutter ( 4384): Receiver: Instance of 'MappedListIterable<Map<String, dynamic>, User>'
I/flutter ( 4384): Tried calling: tolist()
D/EGL_emulation( 4384): app_time_stats: avg=1965.76ms min=1965.76ms max=1965.76ms count=1

检查snapShot.是否有数据的主代码:

Expanded(child: FutureBuilder(
              future: apiService.getUsers(),
              builder: (context, snapShot){
              print(snapShot.error);
                if(snapShot.hasData)
                {
                  return ListView.builder(
                    itemCount: snapShot.data?.length,
                    itemBuilder: (context , index){
                      return GestureDetector(
                        //onTap: (){},
                        child: Container(
                          margin: EdgeInsets.symmetric(horizontal: 10,vertical: 10),
                          padding: EdgeInsets.symmetric(horizontal: 10,vertical: 10),
                          child: ListTile(
                            title: Text('test', style: TextStyle(fontSize: 18, color: Colors.black),) //snapShot.data[index].name
                          ),
                        ),
                      );
                    },
                  );
                }else{
                  return Center(
                    child: CircularProgressIndicator(),
                }

将http get请求发送到API url并检查状态代码是否为200的代码:

class RestAPIService{

  String apiUrl = 'https://mocki.io/v1/ed0c6388-7a27-4c27-942b-f1b6b358178e';

  //// Future method to Get all users from API url | Returns > Response/Error
  Future<List<User>> getUsers() async{

    final response = await http.get(Uri.parse(apiUrl));
    print(response.body);

    //print(response.body);

    //// checking if the request is success with statusCode (200 = OK)
    if(response.statusCode == 200){
      //print(response.body);
      getUsersList(response.body);

    }else{
      throw Exception('Unable to fetch data');
    }
    return getUsers();
  }

  //// Convert response body => user object list
  List<User> getUsersList(String responseBody)
  {
    final parsedBody = json.decode(responseBody).cast<Map<String , dynamic>>();
    return parsedBody.map<User>((json) => User.fromJson(json)).tolist();
  }

}

所有dart文件:https://drive.google.com/drive/folders/1bcDV7eR_n7WgjCcmI1yKZoKRcAQhEylV?usp=sharing
我不知道为什么快照没有数据,但请求的响应有数据。

mv1qrgav

mv1qrgav1#

我所做的只是改变这个

builder: (context, snapShot){

改为:

builder: (context, AsyncSnapshot snapShot){

并按照@pskink的建议将tolist替换为toList

相关问题