Home > Blockchain >  setState() or markNeedsBuild() called during build from changeNotifier
setState() or markNeedsBuild() called during build from changeNotifier

Time:06-25

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

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

CodePudding user response:

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

  • Related