Future Builder在api中有数据,但返回Null

时间:2020-04-03 00:53:17

标签: flutter dart 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函数打印出数据时,我得到了数据。你能告诉我我做错了什么吗?

2 个答案:

答案 0 :(得分:1)

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;

答案 1 :(得分:0)

您可能会从发布请求中获取200或500以外的状态代码。您尚未在代码段的switch语句中处理默认情况。尝试添加默认案例,然后检查是否还有其他错误。