I'm a riverpod newbie.
I think it's a simple code, but it's difficult because it doesn't work. I really don't know the cause.
The counter value is not updated on the UI even when the FloatingActionButton is clicked. Counter value on the UI is still 0.
Why? and How can I update it?
import 'package:flutter/material.dart';
class Counter {
String title;
int value;
Counter(this.title, this.value);
}
final counterProvider = StateProvider<Counter>((ref) {
return Counter('New Counter', 0);
});
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Home());
}
}
class Home extends ConsumerWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
Counter counter = ref.watch(counterProvider);
return Scaffold(
appBar: AppBar(title: Text(counter.title)),
body: Center(
child: Text('${counter.value}'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider).value++,
child: const Icon(Icons.add),
),
);
}
}