Reputation: 1
I'm writting a Flutter app with Riverpod architecture and I need a StateNotifier to keep track of an int that serve to save the current page of a multiscreen form.
Here is my StateNotifier code :
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'multi_step_controller.g.dart';
class MultiStepFormController extends StateNotifier<int> {
MultiStepFormController() : super(0);
void next() => state += 1;
void previous() => state -= 1;
void reset() => state = 0;
void setIndex(int index) => state = index;
}
I wanted to use the Riverpod 3.0 syntax to automaticaly write the provider for this class with this code (and a build of course to generate the part file):
@Riverpod(keepAlive: true)
MultiStepFormController multiStepFormController(MultiStepFormControllerRef ref) {
return MultiStepFormController();
}
But I end up with this error when I want to read the int :
pageController.jumpToPage(currentIndex); The argument type 'MultiStepController' can't be assigned to the parameter type 'int'.
Instead, I changed the code for the provider by manually writting this :
final multiStepFormControllerProvider = StateNotifierProvider<MultiStepFormController, int>((ref) { return MultiStepFormController(); });
And now the code works as intended.
I just want to know why the automatic provider doesn't work like the one I wrote by hand so I can have a better use of automatic generated code from Riverpod in the future. Thanks in advance ! ;-)
Sorry for the code preview, I can't format it properly...
Upvotes: 0
Views: 420
Reputation: 1241
The generator doesn't support StateNotifier
. Use a Notifier/AysncNotifier
instead.
Below is the syntax for defining an equivalent Notifier
using code generation.
@riverpod
class MultiStepFormController extends _$MultiStepFormController {
@override
int build() => 0;
void next() => state += 1;
void previous() => state -= 1;
void reset() => state = 0;
void setIndex(int index) => state = index;
}
Use ref.watch(multiStepFormControllerProvider)
to watch the Notifier
's state.
Use ref.read(multiStepFormControllerProvider.notifier)
to access the Notifier
.
And remember not to declare a constructor for a Notifier/AysncNotifier
class. The Notifier/AysncNotifier
should be initialised using the build
method.
Upvotes: 1