skip to Main Content

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


  1. 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();
        }
      },
    ),
    
    Login or Signup to reply.
  2. 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();
                }
              },
            ),
          ],
        ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search