如何使用 StreamBuilder?

How to use StreamBuilder?

我尝试在我的项目中实现此代码,这是 link 到 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);
    });
  }

我正在我的控制台中打印这个。

[Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot'].

请帮帮我。

你得到了一个 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());
      }
    },
  ),