4

How can I display future value in a Text widget in listview.builder(loop)?. I am calculating distance for each property and want to display in a text widget.

Text('${ _calculateDistance(model, store)' } 

Which returns an "Instance of Future"

Future<double> _calculateDistance(MainModel model, Store store) async {
 double distanceInMeters = await Geolocator().distanceBetween(
    model.postion.latitude,
    model.postion.longitude,
    store.position.latitude,
    store.position.longitude);
return distanceInMeters / 1000;}

For a single post I know I can use setstate, but I am caluclatinng distance for each post.

Nomi
  • 710
  • 3
  • 11
  • 21

1 Answers1

7

You can wrap your item inside a FutureBuilder

@override
  Widget build(BuildContext context) {
    return FutureBuilder<double>(
      future: _calculateDistance( model,  store),
      initialData: 0.0,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text("${snapshot.data}");
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • thanks. just one more question: is it okay to use FutureBuilder in StreamBuilder? Although I have tested and its working fine. Just wanted to know is it good approach or not – Nomi Nov 24 '18 at 15:05
  • actually, I am getting data (places) from firebase using StreamBuilder and then I have to calculate distance using FutureBuilder for each place and display. – Nomi Nov 24 '18 at 16:38
  • Well, you could get the distance on the main method of your streambuilder, but it depends what you want. One pass response or multiple responses like you have now using futurebuilder inside each item. Sorry the missunderstanding – diegoveloper Nov 24 '18 at 16:41