2

Am trying to get the distance two coordinate in a future build which was successful but am looking for how to get the value returned "kmDis" in Text() widget in body: of my code. Check below for my full code.

Future<String> getDistance(String lat, String lng) async {
    final distanceInMeters = await Geolocator().distanceBetween(
        currentLocation.latitude,
        currentLocation.longitude,
        double.parse(lat),
        double.parse(lng));

    double distancekm = distanceInMeters / 1000;
    String kmDis = distancekm.toStringAsFixed(1);
    //int finalkm = distancekm.round();

    return kmDis;
  }

@override
  Widget build(BuildContext context) {

return Scaffold(
        body:Text("i want to return my kmDis value as string here.")
)

  }

yodeveloper
  • 125
  • 2
  • 18

2 Answers2

9

Well, you are dealing with a function that return a Future.

So, you can use a FutureBuilder to operate with this function and respond to different states.

This is a simple code, which deals with a similar situation.

The someFutureStringFunction() is your getDistance().

Also look into the FutureBuilder widget inside the Scaffold()

  Future<String> someFutureStringFunction() async {
    return Future.delayed(const Duration(seconds: 1), () => "someText");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: someFutureStringFunction(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data);
          } else {
            return Text('Loading...');
          }
        },
      ),
    );
  }
encubos
  • 2,915
  • 10
  • 19
0

you can create two methods, one to extract data which you put in a variable and another as like getter (In my case I need to access secure value with plugin flutter_secure_storage without using Futurebuilder)

mixin SecureStorageMethods {
 String keyValue;
 Future<String> _getFromSecureStorage(String key) async {
 keyValue = await slL<FlutterSecureStorage>().read(key: key);
 return keyValue;
}

String getSecureValue(String key) {
 _getFromSecureStorage(key);
 return keyValue;
 }
}

So I call in my code

Text(
      getSecureValue(YOUR_KEY),
      style: OurStyle.textFieldStyle,
    )