【问题标题】:Future Builder has Data in api but, returns NullFuture Builder 在 api 中有数据,但返回 Null
【发布时间】: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 函数打印出数据时,我得到了数据。你能告诉我我在这里做错了什么吗?

【问题讨论】:

    标签: flutter dart future


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      您可能会从发布请求中获得 200 或 500 以外的状态代码。您尚未在代码 sn-p 中处理 switch 语句中的默认情况。尝试添加默认情况并检查是否有其他错误。

      【讨论】:

      • 我在打印语句 Driver Info API: Got Data ${driverProfile.status.user.email} 之后得到数据,一切都在那里。只是不会在未来的建设者中
      猜你喜欢
      • 2021-01-18
      • 2021-06-26
      • 2021-07-30
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多