Future Builder 在 api 中有数据,但是 returns 为空

Future Builder has Data in api but, returns Null

我在调用我的 Future 构建器时得到一个 null。

我的 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)
                );
              }
            }));
  }

控制台 returns "The Drivers data is null" 但是,当我直接从 api 函数打印出数据时,我得到了数据。你能告诉我我在这里做错了什么吗?

您可能从 post 请求中获取 200 或 500 以外的状态代码。您没有在代码段的 switch 语句中处理默认情况。尝试添加默认情况并检查是否存在其他错误。

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;