======== Exception caught by foundation library ====================================================
The following assertion was thrown while dispatching notifications for XXProvider:
setState() or markNeedsBuild() called during build.
This _InheritedProviderScope<XXProvider?> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<XXProvider?>
value: Instance of 'XXProvider'
listening to value
The widget which was currently being built when the offending call was made was: Builder
When the exception was thrown, this was the stack:
#0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:5047:9)
#1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:5059:6)
#2 _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:577:5)
#3 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:433:24)
PROBLEMA:
O erro que você está enfrentando ocorre porque o método setState
está sendo chamado durante a fase de construção do widget, o que não é permitido. O erro é gerado quando o setState
é chamado enquanto o framework está construindo os widgets. Isso pode acontecer se você tentar modificar o estado ou notificar ouvintes (listeners) de um ChangeNotifier
enquanto a árvore de widgets está sendo montada.
@override
void initState() {
super.initState();
_check();
}
Future<void> _checkSegurados() async {
setState(() {
_isLoading =
false; // Oculta o indicador de progresso quando o carregamento é concluído
});
}
SOLUÇÃO:
@override
void initState() {
super.initState();
// Use addPostFrameCallback to avoid calling setState during build
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkSegurados();
});
}