flutter: riverpod setState() or markNeedsBuild() called during build.


setState() or markNeedsBuild() called during build.
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.

エラーを引き起こしたコードはこんな感じです。 debugコンソールに永遠とログが出力されるので実行しないでください。

void main() {
      child: MaterialApp(
    home: Scaffold(
      body: MyBody(),

class CheckController extends StateNotifier<bool> {
  CheckController(state) : super(state);

  toggle() {
    state = !state;

final checkProvider =
    StateNotifierProvider<CheckController, bool>((_) => CheckController(true));

class MyBody extends HookConsumerWidget {
  Widget build(BuildContext context, ref) {
    final controller = ref.watch(checkProvider.notifier);
    final check = ref.watch(checkProvider);
    return Center(
      child: ElevatedButton(
        child: Text('$check'),
        // 本当は ()=> _onPressed(controller)
        onPressed: _onPressed(controller),

  _onPressed(CheckController controller) {



MyBodyのbuildの最中に_onPressed(controller)が実行されてしまい、 中の処理でstateが変わるので、hookが検知して、またbuildが走り、無限ループです。