Increment & Decrement with StateProvider in Riverpod
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final counterProvider = StateProvider<int>((ref) => 0);
void main(){
runApp(ProviderScope(
child: MyStateApp()
// MyApp()
));
}
runApp(ProviderScope(
child: MyStateApp()
// MyApp()
));
}
class MyStateApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return (MaterialApp(
home: const MyHomePage(),
));
}
}
class MyHomePage extends ConsumerWidget{
const MyHomePage ({super.key});
@override
Widget build(BuildContext context,WidgetRef ref){
final count=ref.watch(counterProvider);
// Listen function
ref.listen(counterProvider, (previous, next) {
if(next==5){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('This vlaue is $next')));
}
});
return Scaffold(
appBar: AppBar(
title: Text("State Provider"),
backgroundColor: Colors.pink,
),
body: SafeArea(
child: Column(
children: [
Text("Welcome in StateProvider of Riverpod"),
Text(count.toString()),
ElevatedButton(child: Icon(Icons.add),
onPressed: (){
// ref.read(counterProvider.notifier).state++;
ref.read(counterProvider.notifier).update((state) => state+1);
},
),
ElevatedButton(child: Text("Reset"),
onPressed: (){
// ref.invalidate(counterProvider);
ref.refresh(counterProvider);
},
),
ElevatedButton(child: Icon(Icons.remove),
onPressed: (){
// ref.read(counterProvider.notifier).state--;
ref.read(counterProvider.notifier).update((state) => state-1);
},
),
],
),
),
);
}
}
No comments:
Post a Comment