Reputation: 742
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();
},
)
Upvotes: 0
Views: 604
Reputation: 12673
Try this:
List<User> users = List.from(body).map((e) => User.fromJson(Map.from(e))).toList();
return users;
Upvotes: 1