Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter : Instance of Future<dynamic>

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

Function:

calculation.dart:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading