Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setState() or markNeedsBuild() called during build from changeNotifier

I’m getting this error, and i know it’s because of a line of code where I listen for data from Provider class, so, first question is, does changeNotifier call setState() when it needs to notifyListeners, or is it Provider calling setState or markNeedsBuild, I’m confused, also, please how to solve it, here is my code

here is where I’m using it

BottomNavigationBarItem(
                icon: Badge(
                  showBadge:
                      Provider.of<NotificationsModel>(context, listen: false).unSeen > 0, // this is the problem
                  badgeContent: Text(
                      Provider.of<NotificationsModel>(context, listen: false).unSeen.toString(), // and this
                      style: TextStyle(
                        color: Colors.white,
                        fontFamily: kFontFamily,
                        fontWeight: FontWeight.w600,
                        fontSize: Dimensions.font7,
                      ),
                  ),
                  child: Icon(dModel.index == 2
                      ? Icons.notifications
                      : Icons.notifications_paused_outlined),
                ),
                label: 'Notifications'),

and here is unseen in changeNotifier class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int get unSeen {
    int notSeen = 0;
    for(Notification notification in _notifications) {
      if(notification.isSeen == false) {
        notSeen++;
        notifyListeners();
      }
    }
    return notSeen;
  }

so, please, how can i make it stop trying to build or whatever it’s doing, Thanks

>Solution :

Wrap your notifyListeners(); inside a Future.delayed(Duration.zero, notifyListeners);

this happens when you notifyListeners(); during the build screen process which will fire this exception because you are trying to update your UI while the initial UI is not built yet

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading