【发布时间】:2020-07-15 03:05:14
【问题描述】:
调用我的 Future 构建器时我得到一个空值。
我的 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 函数打印出数据时,我得到了数据。你能告诉我我在这里做错了什么吗?
【问题讨论】: