【问题标题】:Flutter : Instance of Future<dynamic>颤动:未来的实例<动态>
【发布时间】:2023-01-18 20:51:36
【问题描述】:

我正在尝试将函数返回的值打印到屏幕上。

功能: 计算.dart

  Future<dynamic> getTotalCost(BuildContext context) async {
    final user = Provider.of<Userr?>(context, listen: false);
    double totalCost = 0.0;
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('myOrders')
        .doc(user?.uid)
        .collection('items')
        .get();
    for (var doc in snapshot.docs) {
      totalCost += doc["price"];
    }
    print(totalCost.toString());
    return totalCost.toString();
  }

但是它打印的不是 value ,而是 Future 的实例。

  Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text('Item total', style: textStyle),
              Text('${ Provider.of<Calculations>(context, listen: false).getTotalCost(context).toString()}', style: textStyle),
            ],
          ),

我也知道这是因为函数是异步的,它返回未来对象而不是实际值。但是我需要知道如何更改上面的代码才能打印实际值。

【问题讨论】:

    标签: flutter firebase dart


    【解决方案1】:

    试试下面的代码:

    FutureBuilder(
      future: Provider.of<Calculations>(context, listen: false).getTotalCost(context),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text('Item total', style: textStyle),
              Text('${snapshot.data}', style: textStyle),
            ],
          );
        } else if (snapshot.hasError) {
          return Text("Error: ${snapshot.error.toString()}");
        } else {
          return const CircularProgressIndicator();
        }
      },
    ),
    

    【讨论】:

    • 不能将参数类型“String”分配给参数类型“Future<Object?>?”。在第二行得到这个错误。
    • @AswinB 抱歉,那是我的错。我编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2018-01-24
    • 2014-01-26
    • 2016-08-05
    • 2019-11-08
    相关资源
    最近更新 更多