繁体   English   中英

Flutter:未来的实例<dynamic></dynamic>

[英]Flutter : Instance of Future<dynamic>

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

Function:

calculation.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();
  }

但是它打印的不是价值,而是未来的实例。

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

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

试试下面的代码:

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();
    }
  },
),

为了减少Widget的重建次数,同时为了性能优化,我建议只用Future值包装要更新的Widget

通过这样做,您将FutureBuilderbuilder中的Widget树限制为严格必要的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM