Reputation: 65
Now I'm learning Riverpod.
Before this, I do the functionality using the Provider package and there I used ChangeNotifier.
After studying the documentation https://codewithandrea.com/articles/flutter-state-management-riverpod/ i converted my code and used ChangeNotifier again.
Below is my code, I'm trying to understand with a simple example
I have a model
class RiverpodModel extends ChangeNotifier {
String name = 'Name';
void updateName() {
name = 'new';
notifyListeners();
}
ConsumerWidget
final riverpodProvider =
ChangeNotifierProvider<RiverpodModel>((ref) => RiverpodModel());
class ProductPageView extends ConsumerWidget {
const ProductPageView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final model = ref.watch(riverpodProvider);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[100],
elevation: 0,
),
drawer: const DrawerView(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Card'),
const SizedBox(height: 15),
Text(model.name),
const SizedBox(height: 15),
ElevatedButton(
onPressed: () => ref.read(riverpodProvider).updateName(),
child: const Icon(Icons.refresh),
),
],
),
),
);
}
}
The documentation https://codewithandrea.com/articles/flutter-state-management-riverpod/ says that using ChangeNotifier is not the best option.
Please tell me how to do this correctly?
The variable is updated after clicking, you also need to notify the widget where this variable is used about the changes.
I looked at the examples, but could not understand how to do the optimal option, given that I have a model.
I would be grateful for advice or a code example.
Upvotes: 0
Views: 88
Reputation: 13
It's need de constructor
class RiverpodModel extends ChangeNotifier {
String name = 'Name';
RiverpodModel() {
updateName();
}
void updateName() {
name = 'new';
notifyListeners();
}
But I think is easier with anotations
https://riverpod.dev/es/docs/migration/from_change_notifier[enter link description here]1
Upvotes: 0