Flutter : Instance of Future<dynamic>

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.

>Solution :

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

Leave a Reply