2

I have a streambuilder, within, I want to calculate the distance for each different card of the streambuilder. It calculates the distance if I print it in the terminal, but on the screen it shows: Instance of future < String >. Is there a fix for this? I tried making a variable and run set state, but the value has to be different for each card of the streambuilder.

Future<String> distanceInMeters({double uLat, double uLong}) async {
  if (uLat == null && uLong == null) {
    return "";
  } else {
    double distanceInMeters =
        await Geolocator().distanceBetween(uLat, uLong, 52.3546274, 4.8285838);
    String distance = distanceInMeters.toString();
    return "$distance";
  }
}
1
  • can we see the code where you call this method ? Commented Aug 5, 2019 at 20:09

1 Answer 1

1

You will need to use a FutureBuilder. If you are not familar with this widget, you can follow the link to the documentation, which describes the function of the widget extensively.

In practice, it would look something like this:

FutureBuilder(
    future: distanceInmeters(uLat: uLat, uLong: uLong),
    builder: (context, AsyncSnapshot<String> snapshot) {
      if (snapshot.hasError) return Text('${snapshot.error}');
      if (snapshot.hasData) return Text('${snapshot.data}');
      return const CircularProgressIndicator();
    },
  )

The reason you need this is that you are returning your String value from an asynchronous function and thus you need to have some logic that waits to extract the result from the Future.

Sign up to request clarification or add additional context in comments.

4 Comments

Tested the code, but got the text: Futurebuilder <String>
@KarelDebedts You need to use this as a widget and not pass it as a string.
@KarelDebedts How would I know? If you want me to investigate that, you should share the place you are using the widget (probably ask another question).
I am in the exact scenario, below are my codes: Container(child: distanceText(),) -- where the widget is called @creativecreatorormaybenot. Future<String> getDistance( lat, long, lat1, long1) async { return geolocator.distanceBetween(lat, long, lat1, long1).toString(); } Widget distanceText() => FutureBuilder( future: getDistance( lat, long, lat1, long1), builder: (context, AsyncSnapshot<String> snapshot) { if (snapshot.hasData) return Text('${snapshot.data}'); }, ); getting on text: Instance of 'Future<double> not text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.