首页 > 解决方案 > Flutter 在 ListView.builder 中显示未来值

问题描述

如何在 listview.builder(loop) 的 Text 小部件中显示未来值?我正在计算每个属性的距离,并希望在文本小部件中显示。

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

它返回一个“未来的实例”

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;}

对于单个帖子,我知道我可以使用 setstate,但我正在计算每个帖子的距离。

标签: dartflutter

解决方案


您可以将您的物品包装在一个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(),
          );
        }
      },
    );
  }

推荐阅读