Aiman
Aiman

Reputation: 171

Riverpod annotation for State Provider

I am new to Riverpod. I am using Riverpod Annotation to generate providers. As for Future Provider, I did it like this.

@riverpod
Future<void> login(LoginRef ref) async {
  final login = sl<LoginUsecase>();
  final saveAuth = sl<SaveAuthUsecase>();

  final loginForm = ref.read(loginFormProvider);
  final input = LoginUsecaseInput(
    password: loginForm.password!,
    email: loginForm.email!,
  );

  final output = await login(input);

  final saveAuthInput = SaveAuthUsecaseInput(bearerToken: output.bearerToken);

  await saveAuth(saveAuthInput);
}

This is my State Provider

final authStepProvider = StateProvider<AuthStep>((ref) => AuthStep.register);

How to do it with annotations?

I tried:

@riverpod
class AuthStep extends _$AuthStep {
  @override
  AuthStepModel build() {
    return AuthStepModel.register;
  }
}

But when I try to update its state like this:

ref.read(authStepProvider.notifier).state = AuthStepModel.login;

It gives a warning:

The member 'state' can only be used within instance members of subclasses of 'package:riverpod/src/notifier.dart'.

Also, this is for StateNotifier Provider & what I need is StateProvider

Upvotes: 0

Views: 891

Answers (2)

Aiman
Aiman

Reputation: 171

I have found the solution in Riverpod official documentation.

https://riverpod.dev/docs/migration/from_state_notifier

Migrating StateProvider to Notifier.

@riverpod
class AuthStep extends _$AuthStep {
  @override
  AuthStepModel build() => AuthStepModel.register;

  @override
  set state(AuthStepModel newState) => super.state = newState;

  AuthStepModel update(AuthStepModel Function(AuthStepModel state) cb) =>
      state = cb(state);
}

Upvotes: 0

Nagual
Nagual

Reputation: 2088

just add method to mutate state:

@riverpod
class AuthStep extends _$AuthStep {
  @override
  AuthStepModel build() {
    return AuthStepModel.register;
  }
  
  void onLogIn() {
    state = AuthStepModel.login;
  }
}

and call it like this:

ref.read(authStepProvider.notifier).onLogIn();

Upvotes: 0

Related Questions