Replies: 1 comment 3 replies
-
I wrap the code executed in the first step after instantiating the viewModel with a future, without the following errors.
But there have been three rebuilds, the first two are what I want to happen, and the third is not what I want, because it resets the state in the viewModel. |
Beta Was this translation helpful? Give feedback.
-
I want to encapsulate a public widget in order to use,look like this
`class ProviderWidget<T extends ChangeNotifier, R extends ProviderBase>
extends HookWidget {
final R model;
final ValueWidgetBuilder builder;
final Widget? child;
final Function(T)? onModelReady;
ProviderWidget({
Key? key,
required this.model,
required this.builder,
this.child,
this.onModelReady,
});
@OverRide
Widget build(BuildContext context) {
var provider = useProvider(model);
final isMounted = useIsMounted();
}
}`
view_model
`class CountViewModel extends ChangeNotifier {
int count = 0;
add() {
count++;
notifyListeners();
}
}`
main
class Home extends StatelessWidget { @override Widget build(BuildContext context) { final counter = ChangeNotifierProvider<CountViewModel>((ref) => CountViewModel()); return Scaffold( appBar: AppBar(title: const Text('Counter example')), body: ProviderWidget<CountViewModel, ChangeNotifierProvider<CountViewModel>>( model: counter, onModelReady: (model) { model.add(); }, builder: (context, model, child) { return Center(child: Text('${model.count}')); }, ), floatingActionButton: FloatingActionButton( // The read method is an utility to read a provider without listening to it onPressed: () => context.read(counter).add(), child: const Icon(Icons.add), ), ); } }
Then, an error occurred on the execution of the onModelReady function excu
This UncontrolledProviderScope 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.
I did not find any helpful questions or answers, can you point out what I did wrong ?
Beta Was this translation helpful? Give feedback.
All reactions