当我打电话给我的未来建设者时,我得到了一个空值。
我的api设置如下:
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;
});
}对于未来的建设者,我写道:
_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)
);
}
}));
}控制台返回“驱动程序数据为空”,但是,当我直接从api函数输出数据时,就会得到数据。你能告诉我我在这里做错了什么吗?
发布于 2020-04-03 01:45:21
使用await关键字和.then可能会导致一些意想不到的结果。重写函数,只使用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;发布于 2020-04-03 01:33:26
您可能从post请求中获得200或500以外的状态代码。您还没有在代码段中的switch语句中处理默认情况。尝试添加默认情况,并检查是否有其他错误。
https://stackoverflow.com/questions/61003511
复制相似问题