使用StreamBuilder从Firebase获取数据

时间:2019-05-10 04:45:13

标签: dart flutter

我试图从firebase中获取数据,但是当我在initState中对其进行初始化时,该功能无法正常工作。

并且我尝试给它调试打印,它在终端中没有显示,并且在运行应用程序时没有错误或警告。

void _addMarkers(DocumentSnapshot markData) {
    final String markerIdVal = markData.documentID.toString();
    final MarkerId markerId = MarkerId(markerIdVal);

    double lat = double.tryParse(markData['posLat'].toString());
    double long = double.tryParse(markData['posLong'].toString());

    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(
        lat,
        long,
      ),
      infoWindow: InfoWindow(
        title: markData['judul'].toString(), 
        snippet: markData['posLat'] + markData['posLong']
      ),
      icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed) 
    );

    setState(() {
      markers[markerId] = marker;
    });
  }

这是显示标记的功能

{{1}}

1 个答案:

答案 0 :(得分:0)

您需要添加要从Firestore获取的数据的密钥 例如:

// title is the key in the firestore documents, you need to add your key here
addMarkers(snapshot.data.documents[i].data["title"])  

以下代码应为您提供帮助,在本示例中,我从Cloud Firestore获取数据并将其显示在Listview中:

代码:

    @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
        child: StreamBuilder<QuerySnapshot>(
          stream: Firestore.instance.collection("posts").snapshots(),
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError) {
              return new Text('Error: ${snapshot.error}');
            }
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text("Loading..."),
                    SizedBox(
                      height: 50.0,
                    ),
                    CircularProgressIndicator()
                  ],
                ),
              );
            } else {
              return ListView.builder(
                itemCount: snapshot.data.documents.length,
                itemBuilder: (_, index) {
                  return Card(
                      child: ListTile(
                          title: Text(
                              snapshot.data.documents[index].data["title"]),        // getting the data from firestore
                      ),
                   );
                },
              );
            }
          },
        ),
      ),
    );
  }