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.
2
Answers
Try the following code:
In order to reduce the number of
Widget
rebuild, and for performance optimization, I suggest to only wrap theWidget
to update with theFuture
value.By doing so, you limit the
Widget
tree in thebuilder
of theFutureBuilder
to the strict necessary.