How would I use riverpod code generation to create this StateNotifierProvider?

38 views Asked by At

This manually constructed StateNotifier Provider works in Flutter. However, I cannot figure out how to use code gen to make this same thing. Any ideas?

class SessionProvider extends StateNotifier<Session> {
  final Ref ref;

  final sessionManager = singleton<ApiClient>().sessionManager;
  final client = singleton<ApiClient>().client;

  SessionProvider(this.ref, Session initial) : super(initial) {
    init();
  }

  init() {
    updateUser();
  }

  updateUser() async {
    final user = sessionManager.signedInUser;
    // final profile = await client.profile.me();
    state = state.copyWith(
      user: user,
    );
  }
}

Nothing has even come close.

1

There are 1 answers

0
Dhafin Rayhan On

Riverpod code generator won't generate StateNotifier and its provider. Please note that along with Riverpod 2.0, new classes were introduced: Notifier / AsyncNotifer. StateNotifier is now discouraged in favor of those new APIs.

See: From StateNotifier.

The page shows how you can achieve similar thing with Notifier, to make the migration process from StateNotifier easy (see this section). Basically, define a state setter and an update method that works similarly to the ones on StateNotifier.

So you can define a class like this:

@riverpod
class SessionNotifier extends _$SessionNotifier {
  @override
  int build() => Session(); // This should be the value you previously passed to `initial`

  @override
  set state(Session newState) => super.state = newState;
  update(Session Function(int state) cb) => state = cb(state);
}

Edit: On a side note, if you're using StateNotifier, chances are you already use methods to modify the state, so migrating to Notifier will mostly about changing the way you initialize the state. The above code is more relevant if you're migrating from StateProvider.