Created
May 23, 2024 14:55
-
-
Save sgruhier/b391967e51d07496667d8de617f42881 to your computer and use it in GitHub Desktop.
immutable state, correct riverpod example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
// A simple counter class with immutable state | |
class Counter { | |
final int value; | |
Counter(this.value); | |
// Method to return a new instance with an incremented value | |
Counter copyWith({int? value}) { | |
return Counter(value ?? this.value); | |
} | |
} | |
// Creating a StateNotifier for the counter | |
class CounterNotifier extends StateNotifier<Counter> { | |
CounterNotifier() : super(Counter(0)); | |
void increment() { | |
state = state.copyWith(value: state.value + 1); // Creating a new instance with copyWith | |
} | |
} | |
// Creating a provider for the CounterNotifier | |
final counterProvider = StateNotifierProvider<CounterNotifier, Counter>((ref) { | |
return CounterNotifier(); | |
}); | |
void main() { | |
runApp(ProviderScope(child: MyApp())); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar(title: Text('Immutable State Example with StateNotifier')), | |
body: Center(child: CounterWidget()), | |
), | |
); | |
} | |
} | |
class CounterWidget extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
final counter = ref.watch(counterProvider); | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text('Counter value: ${counter.value}'), | |
SizedBox(height: 20), | |
ElevatedButton( | |
onPressed: () { | |
// Calling increment on the notifier | |
ref.read(counterProvider.notifier).increment(); | |
}, | |
child: Text('Increment'), | |
), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment