Flutter - 如何在我未来的构建器文本小部件中获得价值回报

yod*_*per 1 dictionary future widget getdistance flutter

我试图在未来的成功构建中获得两个坐标的距离,但我正在寻找如何在我的代码中的 Text() 小部件中获取返回的“kmDis”值:我的代码。在下面查看我的完整代码。

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.")
)

  }

Run Code Online (Sandbox Code Playgroud)

enc*_*bos 6

好吧,您正在处理一个返回 a 的函数Future

因此,您可以使用 aFutureBuilder来操作此功能并响应不同的状态。

这是一个简单的代码,它处理类似的情况。

someFutureStringFunction()是你的getDistance()

还要看看FutureBuilder里面的小部件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...');
          }
        },
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)