Home > OS >  Flutter : Instance of Future<dynamic>
Flutter : Instance of Future<dynamic>

Time:01-19

I am trying to print a value returned from a function to the screen.

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

But instead printing the value , it prints Instance of Future.

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

I also know the reason that this is due to the function is asynchronous, it returns future object instead of actual value. But I need to know how can I change the above code in order to print the actual value.

CodePudding user response:

Try the following code:

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

CodePudding user response:

In order to reduce the number of Widget rebuild, and for performance optimization, I suggest to only wrap the Widget to update with the Future value.

By doing so, you limit the Widget tree in the builder of the FutureBuilder to the strict necessary.

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