Flutter + Firestore:收听文档更改

时间:2019-11-19 21:00:09

标签: firebase flutter google-cloud-firestore

我正在使用此功能从Firestore获取多个文档:

 getNumbers() async {

    QuerySnapshot snapshot = await Firestore.instance
        .collection('numbers')
        .where("owner", isEqualTo: "${userid}")
        .getDocuments();

    List<myModel> numbersList =
        snapshot.documents.map((doc) => myModel.fromDocument(doc)).toList();

  }

然后我使用listview.builder来显示文档。

但是我想听听变化,那有可能不用streambuilder吗?

我想到了解决方案:侦听更改,然后用新的更改文档替换列表中的文档。有可能吗?

非常感谢您!

1 个答案:

答案 0 :(得分:1)

您可以初始化Firestore流,并在每次获得新元素时调用setState,但这比使用StreamBuilder效率低

class NumberList extends StatefulWidget {
  @override
  _NumberListState createState() => _NumberListState();
}

class _NumberListState extends State<NumberList> {
  //somewhere
  List<MyModel> numbersList = List();


  @override
  void initState() {
    listenNumbers();
    super.initState();
  }

  listenNumbers() {
    Stream<QuerySnapshot> streamNumbers = Firestore.instance
      .collection('numbers')
      .where("owner", isEqualTo: "${userid}")
      .snapshots();

    streamNumbers.listen((snapshot) {
      snapshot.documents.forEach((doc) {
        MyModel obj = MyModel.fromDocument(doc);
        numbersList.add(obj);
        setState(() {

        });
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    return Container(child: ListView.builder(
      itemCount: numbersList.length,
      itemBuilder: (context, index){
        return NumberWidget(
          key: UniqueKey(),
          number: numbersList[index]
        );
      },
    )
    );
  }
}