firebase 如何在列表视图生成器中使用querySnapshot?(flutter)

sz81bmfz  于 2022-12-14  发布在  Flutter
关注(0)|答案(2)|浏览(138)

我正在尝试从我的firebase数据库中获取文档并使用它们创建一个社交媒体提要。这里我正在尝试获取获取的集合的长度,但我无法调用该变量。任何帮助都将不胜感激。Example code

class LoadDataFromFirestore extends StatefulWidget {
  @override
  _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
}

class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
  @override
  void initState() {
    super.initState();
    CollectionReference _collectionRef =
        FirebaseFirestore.instance.collection('fish');

    Future<void> getData() async {
      // Get docs from collection reference
      QuerySnapshot querySnapshot = await _collectionRef.get();

      // Get data from docs and convert map to List
      final allData = querySnapshot.docs.map((doc) => doc.data()).toList();

      print(allData);
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: querySnapshot.docs.length,
        itemBuilder: (BuildContext context, int index) {
          return _postView();
        },
      ),
    );
  }
}
a64a0gku

a64a0gku1#

首先,在initstate中调用future函数是不可以的,你需要像这样使用FutureBuilder

class LoadDataFromFirestore extends StatefulWidget {
  @override
  _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
}

class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
  late CollectionReference _collectionRef;
  @override
  void initState() {
    super.initState();
    _collectionRef = FirebaseFirestore.instance.collection('fish');
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<QuerySnapshot>(
        future: _collectionRef.get(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                QuerySnapshot? querySnapshot = snapshot.data;

                return ListView.builder(
                  itemCount: querySnapshot?.docs?.length ?? 0,
                  itemBuilder: (BuildContext context, int index) {
                    var data = querySnapshot?.docs?[index].data();
                    print("data = $data");
                    return _postView();
                  },
                );
              }
          }
        },
      ),
    );
  }
}

在listview构建器中,您可以使用data来解析数据并使用它。

zte4gxcn

zte4gxcn2#

您可以像这样使用FutureBuilder:

class LoadDataFromFirestore extends StatefulWidget {
  const LoadDataFromFirestore({super.key});

  @override
  State<LoadDataFromFirestore> createState() => _LoadDataFromFirestoreState();
}

class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {

  //TODO change Map<String, dynamic> with your data type with fromJson for example
  Future<List<Map<String, dynamic>>> _getData() async {
    final querySnapshot = await FirebaseFirestore.instance.collection('fish').get();
    return querySnapshot.docs.map((doc) => doc.data()).toList();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<Map<String, dynamic>>>(
        future: _getData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                return _postView(/* Ithink you have to pass here your item like snapshot.data[index]*/);
              },
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

相关问题