setState()或markNeedsBuild()在changeNotifier构建期间调用 &



我得到这个错误,我知道这是因为一行代码,我从提供者类中侦听数据,所以,第一个问题是,changeNotifier调用setState()时需要notifyListeners,或者它是提供者调用setState或markNeedsBuild,我很困惑,也,请如何解决它,这是我的代码

这里是我使用它的地方

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'),

这里在changeNotifier类中是不可见的

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

所以,请,我怎么能让它停止尝试构建或任何它正在做的,谢谢

将您的notifyListeners();包裹在Future.delayed(Duration.zero, notifyListeners);

当你在构建屏幕过程中notifyListeners();会触发这个异常,因为你正在尝试更新你的UI,而初始UI还没有构建

最新更新