Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter + Firestore: listen for document changes

I'm getting multiple documents from firestore with this function:

 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();

  }

Then I use a listview.builder to show the documents.

But I would like to listen to changes, is that possible without using a streambuilder?

I thought of the solution: listen for changes and replace the document of the list with the new changed document. Is that possible?

Thank you very much!

like image 537
Karel Debedts Avatar asked Nov 14 '25 20:11

Karel Debedts


1 Answers

You can initialize your Firestore stream and call setState each time you got new element, but it's less efficient than using 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]
        );
      },
    )
    );
  }
}
like image 124
dubace Avatar answered Nov 17 '25 17:11

dubace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!