Flutter Riverpod Example | State Management

Created At: 2022-04-05 23:22:48 Updated At: 2023-08-17 07:55:49

Flutter Riverpod Example | State Management

We will use four simple steps to create a Riverpod state management counter app

Wrap your app using ProviderScope

Create a provider using StateProvider

Extend ConsumerWidget for a class

Read and edit the value of StateProvider ref.read()

 

Wrap your app using ProviderScope

To work with Flutter Riverpod, go ahead and install it.

dependencies:
  riverpod: ^1.0.3

Let's start with a new project. You can name it anything. In the main.dart file, replace the main() function using the code below

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
  runApp(ProviderScope(
    child: MyApp(),
  ));
}

See how we inject ProviderScope() inside the main() function and we put MyApp() as a child of it.

Now look at MyApp() class. It doesn't change a lot. It looks like below

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home:  MyHomePage(),
    );
  }
}

 

Create a provider using StateProvider

Now we need to create a Provider, because we want to return a value in this counter app and make it reactive. So instead of using pure Provider we will StateProvider

final counterStateProvider = StateProvider<int>((ref) {
  return 0;
});

So whatever StateProvider returns would be reactive. For now, It will return an integer value and it would be reactive. So counterStateProvider is our provider.

Put the above code before MyApp().

Extend ConsumerWidget for a class

Now let's take a look at our MyHomePage class. 

class MyHomePage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 1. watch the counterStateProvider
    final counter = ref.watch(counterStateProvider);
    return Scaffold(
      body: Center(
        child:  Text(
              'Value: $counter',
              style: Theme.of(context).textTheme.headline4,
            )
      ),
    );
  }
}

This class extends ConsumerWidget. Because this class extends ConsumerWidget, we can access the value of StateProvider inside any widget of this class.

So if a class extends ConsumerWidget, you would be able to access the StateProvider value inside this class. At the same time the value, we wanna listen for change we need to wrap that using ref.watch().

 

Read and edit the value using ref.read()

Ok now it's time to create a floating action button

Put the code below body section of Scaffold

floatingActionButton: FloatingActionButton(
        // access the provider via ref.read(), then increment its state.
        onPressed: () => ref.read(counterStateProvider.state).state++,
        child: Icon(Icons.add),
      )

See inside the floating action button, we are using ref.read() to read the value and change it at the same time as we click the button.

ref.watch() is used for watching or observing a value from a provider

ref.read() also does the same thing, but it's used inside a callback function more.

Comment

Add Reviews