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() {
  runApp(ProviderScope(
      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 {
  @override
  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) {
    controller.toggle();
  }
}

onPressedに引数ありでfunctionを渡すときにやりがちです。

引数で、controller(StateNotifier)を渡すのもどうかと思いますが。

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