简体   繁体   中英

snapshot.hasData is true but the snapshot.data.length is null, Flutter

I'm calling an API from a component that returns some data, but the problem is snapshot.hasData is true but the snapshot.data.length is 0 . Am I parsing the data wrong(again)? The code:

API call service component:

Future<List<User>> getUsers() async {
    final response = await APIRequest(Method.GET, '/users');
    if (response.statusCode == 200) {
      var body = jsonDecode(response.body)['data'];
      print('this is the response body: ' + response.body); // it returns data completely
      List<User> users = [];
      body.map((e) {
        User user = User.fromJson(e);
        users.add(user);
      });
      return users;
    } else {
      print('Error occurred! Data is not fetched!');
    }
  }

The user list component:

Future<List<User>> _getUserList() async {
    var _userData = await APIcalls.instance.getUsers();
    return _userData;
  }

FutureBuilder<List<User>>(
                    future: _getUserList(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        print(snapshot.hasData.toString()); // returns true
                        print(snapshot.data.length); // returns 0
                        return ListView.builder(
                          shrinkWrap: true,
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                            print(snapshot.data.length);

                            return Text(snapshot.data[index].userId);
                          },
                        );
                      } else if (snapshot.hasError) {
                        return Text("${snapshot.error}");
                      }
                      return Container();
                    },
                  )

Try this:

 List<User> users = List.from(body).map((e) => User.fromJson(Map.from(e))).toList();
 return users;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM