Skip to content

Instantly share code, notes, and snippets.

@sgruhier
Created May 23, 2024 14:49
Show Gist options
  • Save sgruhier/a6ab792c7e5567f36f1ba73643beb2db to your computer and use it in GitHub Desktop.
Save sgruhier/a6ab792c7e5567f36f1ba73643beb2db to your computer and use it in GitHub Desktop.
mutable state, wrong riverpod example
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// A simple counter class with mutable state
class Counter {
int value;
Counter(this.value);
}
// Creating a StateNotifier for the counter
class CounterNotifier extends StateNotifier<Counter> {
CounterNotifier() : super(Counter(0));
void increment() {
state.value++; // Directly mutating the state
// No state assignment here, so UI may not update
}
}
// 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('Mutable 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