为什么当我向firebase添加数据时,数据一直循环?

w46czmvw  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(142)

我是flutter和firebase的新手,我不知道为什么当我上传任何数据到firebase时,数据会不断重复相同的事情,但当我热重启上传项回到1时,这是我的代码:

Future getDocId() async {
await FirebaseFirestore.instance
    .collection('users')
    .orderBy('mobile', descending: true)
    .get()
    .then(
      (snapshot) => snapshot.docs.forEach(
        (document) {
          print(document.reference);
          docIDs.add(document.reference.id);
        },
      ),
    );

}

body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Expanded(
          child: FutureBuilder(
            future: getDocId(),
            builder: (context, snapshot) {
              return ListView.builder(
                itemCount: docIDs.length,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.all(10.0),
                    child: ListTile(
                      title: ReadUser(documentId: docIDs[index]),
                      tileColor: Colors.purple[100],
                    ),
                  );
                },
              );
            },
          ),
        ),

这是我未来的建筑师

return FutureBuilder<DocumentSnapshot>(
  future: users.doc(documentId).get(),
  builder: ((context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      Map<String, dynamic> data =
          snapshot.data!.data() as Map<String, dynamic>;
      return Text('Name:' +
          '${data['name']}' +
          "\n"
              'Email:' +
          '${data['email']}' +
          "\n"
              'Mobile Number:' +
          '+' +
          '${data['mobile']}' +
          "");
    }
    return Text('Loading..');
  }),
);
bnl4lu3b

bnl4lu3b1#

获取数据的方式是错误的,而不是将结果传递给外部变量,您需要像这样返回它,我假设docID是一个字符串列表:

Future<List<String>> getDocId() async {
    try {
      var snapshot = await FirebaseFirestore.instance
          .collection('users')
          .orderBy('mobile', descending: true)
          .get();
      return snapshot.docs.map((document) => document.reference.id).toList();
    } catch (e) {
      return [];
    }
  }

然后将FutureBuilder更改为:

FutureBuilder<List<String>>(
  future: getDocId(),
  builder: (context, snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.waiting:
        return Text('Loading....');
      default:
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        } else {
          List<String> data = snapshot.data ?? [];
          return ListView.builder(
            itemCount: data.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: const EdgeInsets.all(10.0),
                child: ListTile(
                  title: ReadUser(documentId: data[index]),
                  tileColor: Colors.purple[100],
                ),
              );
            },
          );
        }
    }
  },
),

相关问题