Riverpod in Flutter – Simplest Example Ever

By | June 22, 2023
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:

  1. Import the required packages:
    • package:flutter/material.dart for Flutter widgets.
    • package:flutter_riverpod/flutter_riverpod.dart for Riverpod.
  2. Create a countProvider using the Provider class from Riverpod. The provider’s value is an int with an initial value of 0.
  3. In the main() function, wrap the MyApp widget with a ProviderScope to provide access to the providers.
  4. Define the MyApp widget, which is a stateless widget.
  5. In the MyApp widget’s build method, create a MaterialApp widget as the root widget.
  6. Inside the MaterialApp, create a Scaffold widget with an AppBar and a body that contains a Center widget.
  7. Inside the Center widget, use the Consumer widget from Riverpod to subscribe to the countProvider. The builder function is called whenever the value of the provider changes. Display the count using a Text widget.
  8. Add a floatingActionButton to the Scaffold to increment the count when pressed. Use context.read(countProvider) to access the state of the provider and update its value.
  9. Run the application using runApp() and provide the MyApp 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.

Leave a Reply

Your email address will not be published. Required fields are marked *