【问题标题】:The argument type 'Future<int>' can't be assigned to the parameter type 'int'参数类型“Future<int>”不能分配给参数类型“int”
【发布时间】:2020-12-03 05:35:31
【问题描述】:

我是 Flutter 的新手,我一直在尝试使用 PHP API 后端开发应用程序。在无数的答案和在线研究中,我无法找到解决我面临的问题的方法。我希望有人可以就我做错的地方给我意见。

我正在尝试从我的 API 中获取数据以显示在卡片中。以下是我的代码:

...previous unnecessary code

      Padding(
          padding: EdgeInsets.symmetric(horizontal: 25.0, vertical: 30.0),
          child: Text('Summary Report',
              style: TextStyle(
                  color: Colors.black.withOpacity(0.7),
                  fontWeight: FontWeight.bold,
                  fontSize: 20.0))),
      Padding(
        padding: EdgeInsets.only(left: 15.0, bottom: 25.0, right: 15.0),
        child: Container(
          height: 150.0,
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: <Widget>[
              UpcomingCard(
                  title: 'Total Service Calls',
                  value: _getTotalCalls(), //this is where I want to display my data
                  color: Colors.blue),
              UpcomingCard(
                  title: 'Pending Service Calls',
                  value: 0,
                  color: Colors.red),
            ],
          ),
        ),
... other unnecessary code

//function to get data
Future<int> _getTotalCalls() async {
  SharedPreferences localStorage = await SharedPreferences.getInstance();
  var user_id = localStorage.getString('user_id');
  var data = {'user_id': user_id};
  var res = await CallApi().postData(data, 'service/total');
  var body = json.decode(res.body);
  if (body['success']) {
    return body['servicecall_total'];
  } else {
    return 0;
  }
}

希望得到一些帮助。谢谢

【问题讨论】:

    标签: android-studio flutter dart


    【解决方案1】:

    当你想显示未来函数的结果时,你需要使用 FutureBuilder

    FutureBuilder<int>(
      future: _getTotalCalls(),
      initalData: 0,
      builder: (context, snapshot) {
        return UpcomingCard(
                  title: 'Total Service Calls',
                  value: snapshot.data.toString(), 
                  color: Colors.blue)
      }
    )
    

    【讨论】:

    • 你是救生员!唯一的事情是我不得不使用 toInt() 而不是 toString()。谢谢。
    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多