listview - Flutter - 为每个 ListView 项运行异步函数

标签 listview geolocation flutter

我有一个位置列表,我在 Listview Builder 中检索和显示。

每个位置都有一个纬度和经度值。

我现在尝试使用 GeoLocator 插件 ( https://pub.dartlang.org/packages/geolocator ) 将“距离”字段包含到 ListView 中 - 通过使用“查找最近”按钮获取用户位置,然后使用用户的纬度/经度计算距离以及每个位置的纬度/经度。

由于“GeoLocator 计算距离方法”是异步的,我无法插入 Geolocator().distanceBetween(userLat, userLon、storeLat、storeLon) 直接添加到小部件中。

问题: 那么我该怎么做,当用户点击“查找最近的”按钮时,每个 Listview 项目都通过 getDistance 方法传递并返回结果?

简化代码:

Future<List> getdata() async {
final response = await http.get(getStoreLocations);
return json.decode(response.body);
}


@override
Widget build(BuildContext context) {
return new Scaffold(
  appBar: new AppBar(title: new Text("Location"),),
  body: new FutureBuilder<List>(
    future: getdata(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? new BrowseStoreLocation(
          list: snapshot.data,)
          : new Center(
        child: new CircularProgressIndicator(),
      );
    },
  ),
);
}
}

GeoLocator 获取用户位置方法:

getLocation () async {
Position position = await Geolocator().getCurrentPosition(LocationAccuracy.best);
userLat = position.latitude;
userLon = position.longitude;
setState(() {

});
}

GeoLocator 计算距离方法:

getDistance()async {
double distanceInMeters = await Geolocator().distanceBetween(userLat, 
userLon, storeLat, storeLon);
distance = distanceInMeters/1000;
}

我尝试通过设置变量进行试验。打印显示所有项目的 storeLat 和 storeLon 值,但仅计算并返回最后一个列表项。

String storeLat = "";
String storeLon = "";
getDistance(storeLat,storeLon)async {
double distanceInMeters = await Geolocator().distanceBetween(userLat, userLon, double.parse(storeLat), double.parse(storeLon));
distance = distanceInMeters/1000;
setState(() {
});
}

new ListView.builder(
itemCount: widget.list == null ? 0 : widget.list.length,
itemBuilder: (context, i) {
storeLat = widget.list[i]['latitude'];
storeLon = widget.list[i]['longitude'];
print(storeLon+storeLat);
return Container(
child: Column(
children: <Widget>[
new Text(distance.toString())
],
),

最佳答案

你必须使用 FutureBuilder为此目的,在您的 ListView.builder 中然后必须在其中调用您的方法 getDistance

ListView.builder(
  itemCount: locationsList.length,
  itemBuilder: (context, position) {
    final current = locationsList[position];
    return FutureBuilder<String>(
      future: getDistance(current.latitude, current.longitude)
                   .then((location) => location.toString()),
      builder: (context, snapshot) {
        return Container(
          child: Column(
            children: <Widget>[new Text(snapshot.data)],
          ),
        );
     });
});

关于listview - Flutter - 为每个 ListView 项运行异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359405/

相关文章:

android - 查找附近的应用用户(iPhone 和 Android)

regex - 将城市名称和地理位置数据添加到数据框

flutter - 如何在 Flutter 中更改 DropdownButton 的选定索引

android - 使用键盘时,ListView 不会滚动到末尾

firebase - 新增: '_InternalLinkedHashMap<String, dynamic>'类型不是 'DocumentSnapshot'类型的子类型

android - Listview行requestLayout()和View回收

dart - 滚动 Controller 未附加到任何 ScrollView

android - 从 ExpandableListView (Android) 在 ChildView 中添加标题

react-native - 如何在 native react 中进行反向地理编码

Flutter 2.0 - 如何在按下时更改文本按钮的初始颜色