Reputation: 800
I am getting a null when calling my Future builder.
I have my api setup like this:
Future getDriverInfo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var _token = prefs.getString('token');
var dProfile;
var url =
'http://buddies-8269.herokuapp.com/api/driver/current_user/?access=$_token';
await http.post(url, headers: {"Content-Type": "application/json"}).then(
(http.Response response) {
switch (response.statusCode) {
case (200):
var responseData = json.decode(response.body);
DriverProfile driverProfile = DriverProfile.fromJson(responseData);
print('Driver Info API: Got Data ${driverProfile.status.user.email}');
dProfile = driverProfile.status;
break;
case (500):
print('500 Error ${response.body}');
break;
}
return dProfile;
});
}
For the future builder I wrote:
_getInfo = getDriverInfo();
Widget _buildDataWidget() {
return Container(
height: 10,
child: FutureBuilder(
future: getDriverInfo(),
builder: (context, snapshot) {
if (!snapshot.hasData == null) {
return Center(child: CircularProgressIndicator());
} else {
var x = snapshot.data;
print('The Drivers data is $x');
return Container(
child:Text(x)
);
}
}));
}
The console returns "The Drivers data is null" but, when I print out the data directly from the api function, I get data. Could you let me know what I've done wrong here.
Upvotes: 0
Views: 365
Reputation: 1896
Using the await
keyword together with .then
might be causing some unexpected outcomes. Rewrite the function to just use await
.
http.Response response = await http.post(url, headers: {"Content-Type": "application/json"})
switch (response.statusCode) {
case (200):
var responseData = json.decode(response.body);
DriverProfile driverProfile = DriverProfile.fromJson(responseData);
print('Driver Info API: Got Data ${driverProfile.status.user.email}');
dProfile = driverProfile.status;
break;
case (500):
print('500 Error ${response.body}');
break;
}
return dProfile;
Upvotes: 1
Reputation: 101
You might be getting status code other than 200 or 500 from post request. You've not handled default case in switch statement in your code snippet. Try adding a default case and check if there's some other error.
Upvotes: 0