Here is the Riverpod 2.0 Counter app example. Here we covered how to do both increment and decrement. We have done it using two floating action buttons.
Let’s see the Riverpod 2.0 provider both for increment and decrement.
@Riverpod(keepAlive: true)
class HomeIndexController extends _$HomeIndexController{
@override
int build(){
return 0;
}
void increment(){
state = state+1;
print(state);
//
}
void decrement(){
state = state-1;
print(state);
}
}
Here we used Riverpod code generation tool to create or generate Riverpod provider. Here we actually created HomeIndexController which extends _$HomeIndexController. We have also have a build() method which returns int type. Each of the method can access state object of Riverpod package.
Let’s see the UI code how it works
class MyHomePage extends ConsumerWidget {
const MyHomePage({
super.key,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
//var count = ref.watch(homeIndexControllerProvider);
// var x = Provider.of<ProviderType>(context).getProviderMethod();
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text("Riverpod app"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
"Test",
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FloatingActionButton(
heroTag: "one",
onPressed: (){
ref.read(homeIndexControllerProvider.notifier).increment();
},
tooltip: 'Increment',
child: Icon(Icons.add, size: 36,),
),
FloatingActionButton(
heroTag: "one",
onPressed: (){
ref.read(homeIndexControllerProvider.notifier).decrement();
},
tooltip: 'Increment',
child: Icon(Icons.remove, size: 36,),
),
],
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Here we have ConsumerWidget instead of Stateful or Stateless class. One floating action button is responsible for incrementing and the other one is for decrementing.
Make sure you have MyApp() class called from main() method.
Good article for Riverpod, thanks for share brother!
– Rafah
You are most welcome. Keep up the learning. Another riverpod advanced course https://youtu.be/8NiL0VTHBfk