【问题标题】:How to send custom data to future builder?如何将自定义数据发送给未来的构建器?
【发布时间】:2020-04-18 01:53:02
【问题描述】:

我正在尝试找到离我当前位置最近的人。所以我正在从 firestore 获取所有文件。

我的firestore结构是这样的,

所以我正在获取所有用户并通过计算距离来检查最近的用户,并且我想将过滤后的数据传递给未来的构建器以查看。

Future makeRequest() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
         .///
        .collection('mechanic')
        .getDocuments();

    final Distance distance = new Distance();

    qn.documents.forEach((f) {
      double km = distance.as(
          LengthUnit.Kilometer,
          new LatLng(f.data['location'].latitude, f.data['location'].longitude),
          new LatLng(widget.lat, widget.lan));
      if (km < f.data['radius']) {
        print(f.data);
        // filtering data and want to pass this filterd data to Future builder
      }
    });

    return qn.documents;
  }
body: FutureBuilder(
            future: makeRequest(),
            builder: (_, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: Text("Loading..."),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemExtent: 100.0,
                  itemBuilder: (_, index) {
                    return ListTile(
                      title: Text(
                        snapshot.data[index].data['name'],
                    );
                  },
                );
              }
            })

如何解决这个问题?

【问题讨论】:

  • 这里有什么问题?你有任何错误吗?
  • @easeccy 否。从 if 语句中,我试图过滤获取的数据,我只想将其传递给 Future 构建器。但在上面的代码中,'qn.documents;'的返回只是将所有获取的值返回给未来的构建器。但我只想返回过滤后的数据

标签: android firebase flutter dart google-cloud-firestore


【解决方案1】:

您可以将结果累积到一个列表中并返回该列表。

Future makeRequest() async {
   var results =[];
   var firestore = Firestore.instance;
   QuerySnapshot qn = await firestore
   .///
       .collection('mechanic')
      .getDocuments();

   final Distance distance = new Distance();

   qn.documents.forEach((f) {
       double km = distance.as(
       LengthUnit.Kilometer,
       new LatLng(f.data['location'].latitude, f.data['location'].longitude),
       new LatLng(widget.lat, widget.lan));
       if (km < f.data['radius']) { 
           results.add(f.data);
       }

   });

   return results;
}

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2021-11-22
    • 2017-08-19
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多