如何使用StreamBuilder?

时间:2020-07-29 09:57:32

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

我尝试在我的项目中实现此代码,这是指向https://gitmemory.com/issue/DarshanGowda0/GeoFlutterFire/16/472098428

的链接

这是我的脚手架。

Scaffold(
          body: Center(
        child: Column(
          children: <Widget>[
            FloatingActionButton(
              onPressed: () async  {

             await GetusersLocation();

              },
              child: Center(
                child: Icon(
                  Icons.add,
                ),
              ),
            ),

            StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {
                  print(snapshots.data);
                  return Container();
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

          ],
        ),
      )),

这是我的GetusersLocation()

Future<void> GetusersLocation() async {
    Position position = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    lat = position.latitude;
    long = position.longitude;
  }

这是我的initState()


Stream<List<DocumentSnapshot>> stream;



  @override
  void initState() {
    super.initState();
    geo = Geoflutterfire();
    var radius = BehaviorSubject.seeded(1.0);
    GeoFirePoint center = geo.point(latitude: 26.8462924, longitude: 81.0042322);
    stream = radius.switchMap((rad) {
      var collectionReference = _firestore.collection('locations');
      return geo.collection(collectionRef: collectionReference).within(
          center: center, radius: rad, field: 'position', strictMode: true);
    });
  }

我要在控制台上打印出来。

[“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例,“ DocumentSnapshot”的实例]。

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您有一个DocumentSnapshot列表,这很正常,您的数据在DocumentSnapshot中。 您可以像这样在ListView中使用DocumentSnapshot的列表。

 StreamBuilder(
    stream: stream,
    builder: (BuildContext context,
        AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
      if (snapshots.connectionState == ConnectionState.active &&
          snapshots.hasData) {
        print(snapshots.data);
        return ListView.builder(
          itemCount: snapshots.data.length,
          itemBuilder: (BuildContext context, int index) {
            DocumentSnapshot doc = snapshots.data[index];
            Map location = doc.data; // this is your data which is probably a map
            return Text(
              location.toString(),
            );
          },
        );
      } else {
        return Center(child: CircularProgressIndicator());
      }
    },
  ),