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...
The generator doesn't support
StateNotifier. Use aNotifier/AysncNotifierinstead.Below is the syntax for defining an equivalent
Notifierusing code generation.Use
ref.watch(multiStepFormControllerProvider)to watch theNotifier's state.Use
ref.read(multiStepFormControllerProvider.notifier)to access theNotifier.And remember not to declare a constructor for a
Notifier/AysncNotifierclass. TheNotifier/AysncNotifiershould be initialised using thebuildmethod.