Open mirette3 opened 2 years ago
A state-management library that:
package name | description |
---|---|
Allows using both flutter_hooks and Riverpod together. | |
A basic way of using Riverpod for Flutter applications | |
A version of Riverpod with all the classes related to Flutter stripped out. |
For widgets to be able to read providers, we need to wrap the entire application in a "ProviderScope" widget.
void main() {
runApp(ProviderScope(child: MyApp(),),);
}
Providers are the most important part of a Riverpod application. A provider is an object that encapsulates a piece of state and allows listening to that state.
final myProvider = Provider((ref) =>MyValue());
in Riverpod we can have two providers expose a state of the same "type":
final cityProvider = Provider((ref) => 'London');
final countryProvider = Provider((ref) => 'England');
dependencies:
riverpod: ^last_version
import 'package:riverpod/riverpod.dart';
wrap MyApp "ProviderScope" widget
void main() {
runApp(ProviderScope(child: MyApp(),),);
}
Create a Provider
final nameProvider = Provider<String>( (ref)=>'name'); //this is global
Consume the Provider // in this case rebuild all widget
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final nameP = ref.watch(nameProvider);
return Text(nameP);
}
}
Consume the Provider // in this case build specific widget Text Only
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer( builder:(context,ref,child)=> Text(ref.watch(nameProvider)));
}
}
Advantages
Install RiverPod
-add the latest version of flutter_riverpod as a dependency to our (pubspec.yaml) file. -wrap our root widget in void main with a ProviderScope.
Steps to Create a provider
1- add Global provider
2- read the provider value inside the widget, we have two ways:
Note