import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final countProvider = Provider<int>((ref) => 0);
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Riverpod Example',
home: Scaffold(
appBar: AppBar(title: Text('Riverpod Example')),
body: Center(
child: Consumer(
builder: (context, watch, child) {
final count = watch(countProvider);
return Text('Count: $count', style: TextStyle(fontSize: 24));
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read(countProvider).state++,
child: Icon(Icons.add),
),
),
);
}
}
In this example, we create a simple Flutter application that displays a counter and increments the count when a FloatingActionButton is pressed. The state management is handled by Riverpod.
Here’s a breakdown of the code:
- Import the required packages:
package:flutter/material.dart
for Flutter widgets.package:flutter_riverpod/flutter_riverpod.dart
for Riverpod.
- Create a
countProvider
using theProvider
class from Riverpod. The provider’s value is anint
with an initial value of 0. - In the
main()
function, wrap theMyApp
widget with aProviderScope
to provide access to the providers. - Define the
MyApp
widget, which is a stateless widget. - In the
MyApp
widget’sbuild
method, create aMaterialApp
widget as the root widget. - Inside the
MaterialApp
, create aScaffold
widget with anAppBar
and abody
that contains aCenter
widget. - Inside the
Center
widget, use theConsumer
widget from Riverpod to subscribe to thecountProvider
. The builder function is called whenever the value of the provider changes. Display the count using aText
widget. - Add a
floatingActionButton
to theScaffold
to increment the count when pressed. Usecontext.read(countProvider)
to access the state of the provider and update its value. - Run the application using
runApp()
and provide theMyApp
widget as the root.
When you run this code, you will see a simple app with an app bar, a counter in the center of the screen, and a floating action button that increments the counter when pressed.
This example demonstrates the basic usage of Riverpod for state management in Flutter. You can extend and build upon this foundation to handle more complex state and implement more features in your Flutter application.