Home > Enterprise >  Flutter - build loop problems in notifyListeners()
Flutter - build loop problems in notifyListeners()

Time:08-05

I have been get document data from firestore using provider. And I'm using notifyListeners() to apply this data in real time.

However, if I use notifyListeners() in this method, it falls into the build loop when I call this method.

  void getCurrentPageModel(String roomKey) async {
    await FirebaseFirestore.instance
        .collection(COL_ROOMS)
        .doc(roomKey)
        .collection(COL_PAGES)
        .where(DOC_PAGE, isEqualTo: _currentPage) 
        .get()
        .then((snapshot) {
      for (var doc in snapshot.docs) {
        // get model data
        _pageModel = PageModel(
          uid: doc.data()[DOC_UID],
          page: doc.data()[DOC_PAGE],
          createdDate: doc.data()[DOC_CREATEDATE].toDate(), 
        );
      }
    }).catchError((e) => logger.w(e));
     notifyListeners(); // loop error!
  }

call provider method

  @override
  Widget build(BuildContext context) {
    context.read<PageProvider>().getCurrentPageModel(widget.roomKey);
 }

Removing the firestore code from this provider method will eliminate the problem.

Can I know the cause of this?

CodePudding user response:

You are already using then, no need to use await.

  void getCurrentPageModel(String roomKey) async {
     FirebaseFirestore.instance
        .collection(COL_ROOMS)
        .doc(roomKey)
        .collection(COL_PAGES)
        .where(DOC_PAGE, isEqualTo: _currentPage) 
        .get()
        .then((snapshot) {
      for (var doc in snapshot.docs) {
        // get model data
        _pageModel = PageModel(
          uid: doc.data()[DOC_UID],
          page: doc.data()[DOC_PAGE],
          createdDate: doc.data()[DOC_CREATEDATE].toDate(), 
        );
      }
     notifyListeners(); //there
    }).catchError((e) => logger.w(e));
    
  }
  • Related