avoid_notifier_constructors
v0.4.0 Warning Fix Bloc / Riverpod
This rule flags Notifier and AsyncNotifier subclasses that have constructors with non-empty bodies or initializer lists. Empty constructors are allowed. All initialization logic should go into the build() method instead.
Why use this rule
Section titled “Why use this rule”Riverpod creates and recreates Notifiers as part of its lifecycle management. The build() method is the proper place for initialization because it runs at the right time in the provider lifecycle and has access to ref. Constructor logic runs before the Notifier is fully wired up, which means you can’t use ref there, and the logic won’t re-run when the provider is refreshed or invalidated.
See also: Riverpod providers
import 'package:riverpod/riverpod.dart';
// Constructor with bodyclass BadCounter extends Notifier<int> { var _initial = 0;
BadCounter() { _initial = 1; }
@override int build() => _initial;}
// Constructor with initializer listclass BadCounter2 extends Notifier<int> { final int _initial;
BadCounter2() : _initial = 1;
@override int build() => _initial;}import 'package:riverpod/riverpod.dart';
// No constructor, initialization in build()class GoodCounter extends Notifier<int> { @override int build() => 0;
void increment() => state++;}
// Empty constructor is fineclass GoodCounter2 extends Notifier<int> { GoodCounter2();
@override int build() => 0;}Configuration
Section titled “Configuration”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
avoid_notifier_constructors: true.
To turn it off:
rules: avoid_notifier_constructors: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_public_notifier_properties— Prevent public fields, getters, and setters on Notifier classes.notifier_build— Classes annotated with @riverpod must define a build method.protected_notifier_properties— A Notifier’s state, ref and future should not be used from outside the notifier.avoid_bloc_public_methods— Prevent public methods, getters, and setters in Bloc classes.