列表视图. firebase中的构建器

mrfwxfqh  于 2022-11-25  发布在  其他
关注(0)|答案(2)|浏览(150)

我这里有这段代码,它应该是从firebase中的一个文档构建一个列表,但最终失败了,因为它总是转到return loading。据我所知,这与它是一个未来有关,我认为我访问它是错误的。我试过以文本的形式输出,它能工作,但作为一个列表视图,它不能。
我也试着在上面做一个异步的函数,但是应用程序仍然输出加载。任何帮助都将不胜感激。

Widget showFriend() {
CollectionReference users = FirebaseFirestore.instance.collection('todos');
return FutureBuilder<DocumentSnapshot>(
    future: users.doc(documentId).get(),
    builder:
        (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (snapshot.hasError) {
        return Text("Something went wrong");
      }

      if (snapshot.hasData && !snapshot.data!.exists) {
        return Text("Document does not exist");
      }

      if (snapshot.connectionState == ConnectionState.done) {
        Map<String, dynamic> data =
            snapshot.data!.data() as Map<String, dynamic>;
        List<dynamic> fren = [];

        void waitList() async {
          List<dynamic> temp;
          temp = await (data['friends']);
          fren = temp;
        }

        waitList();

        fren = List.from(data['friends']);
        print(fren);
        if (fren.length > 0) {
          ListView.builder(
              itemCount: fren.length,
              itemBuilder: (context, index) {
                return ListTile(title: Text('${fren[index]}'));
              });
        }
      }
      return Text("loading");
    });
}
jjhzyzn0

jjhzyzn01#

ListView之前缺少return

if (fren.length > 0) {
   return ListView.builder( //here
j2qf4p5b

j2qf4p5b2#

请尝试以下操作:

Widget showFriend() {
  CollectionReference users =
      FirebaseFirestore.instance.collection('todos');
  // ignore: newline-before-return
  return FutureBuilder<DocumentSnapshot>(
    // future: users.doc(documentId).get(),
    // ignore: prefer-trailing-comma
    builder:
        (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (snapshot.hasError) {
        return Text("Something went wrong");
      }

      if (snapshot.connectionState == ConnectionState.done) {
        if (snapshot.hasData) {
          if (!snapshot.data!.exists) {
            return Text("Document does not exist");
          } else {
            Map<String, dynamic> data =
                snapshot.data!.data() as Map<String, dynamic>;
            List<dynamic> fren = [];

            List<dynamic> temp;
            temp = data['friends'];
            fren = temp;

            fren = List.from(data['friends']);
            print(fren);
            if (fren.length > 0) {
              ListView.builder(
                  itemCount: fren.length,
                  itemBuilder: (context, index) {
                    return ListTile(title: Text('${fren[index]}'));
                  });
            }
          }
        }
      }
   return Text("loading");
    },
  );
}

相关问题