Skip to main content

State Management Solutions in Flutter: A Practical Guide to Riverpod

State Management Solutions in Flutter: A Practical Guide to Riverpod

Understand how Riverpod manages app state, how it compares with other Flutter approaches, and how to build maintainable features with providers, AsyncValue, and Notifier.

As a Flutter application grows, state management becomes an important architectural decision. A simple screen may only need a local setState(), while an application with authentication, API requests, shared preferences, and complex workflows needs a more structured approach.

Riverpod is a state-management and dependency-injection solution for Dart and Flutter. It helps separate business logic from widgets, exposes state through providers, and makes dependencies easier to replace in tests. This guide uses modern Riverpod 2-style APIs. Some APIs differ between major versions, so check the documentation for the version installed in your project.

What you’ll learn

  • What state management means in Flutter
  • How Riverpod works and when to choose it
  • How to install Riverpod and configure the app
  • How to use Provider, Notifier, and FutureProvider
  • How to handle loading, success, and error states
  • How to test providers and structure a production app

1. What is state management?

State is information that can affect what your app displays or how it behaves: a selected tab, cart items, the current user, API results, a loading flag, or form validation status.

Flutter provides local state tools such as setState(). These are excellent for state used by a single widget. When state must be shared across widgets or coordinated with repositories and services, a dedicated approach can make the code easier to reason about.

ApproachGood fitConsiderations
setState()Small, local widget stateCoordination can become hard across distant widgets
Provider / ChangeNotifierSimple shared state and existing Provider appsNeeds clear ownership and notification discipline
BLoC / CubitExplicit event/state flows and team conventionsMay add boilerplate for simple features
RiverpodShared state, dependency injection, async data, testingRequires learning provider types and lifecycle behavior
GetXCompact APIs for several app concernsAgree on conventions for dependencies and responsibilities

No solution is best for every project. Consider team experience, app complexity, testing requirements, and existing architecture rather than choosing a package based only on popularity.

2. What is Riverpod?

Riverpod lets you declare providers that expose values, state, or services. Widgets can listen to providers and rebuild when relevant state changes. Providers can also be read from Dart code and overridden in tests.

  • Separation of concerns: business logic can live outside widget classes.
  • Dependency injection: repositories and services can be exposed as providers and replaced in tests.
  • Async state support: asynchronous providers can represent loading, data, and error outcomes.
  • Reactive UI: widgets update when the state they watch changes.
  • Lifecycle options: providers can be disposed or retained according to configuration and usage.

Riverpod is related to the original Provider package, but it has distinct provider declarations, container concepts, and testing patterns.

3. Install Riverpod

For Flutter UI applications, add flutter_riverpod using the version compatible with your Flutter and Dart SDK:

flutter pub add flutter_riverpod

Code generation is optional. The examples below use manual provider declarations to keep the fundamentals clear. Wrap the application with ProviderScope, usually near the root in lib/main.dart:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: CounterPage());
  }
}

ProviderScope creates the provider container that Flutter widgets use to access Riverpod state. Most apps only need one root scope.

4. Create your first counter with Notifier

For mutable app state, Notifier is a useful modern API to learn. The notifier owns state and exposes methods that describe allowed changes. Create lib/counter_provider.dart:

import 'package:flutter_riverpod/flutter_riverpod.dart';

class Counter extends Notifier<int> {
  @override
  int build() => 0;

  void increment() => state++;
  void decrement() => state--;
  void reset() => state = 0;
}

final counterProvider = NotifierProvider<Counter, int>(
  Counter.new,
);

Use it in a ConsumerWidget:

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'counter_provider.dart';

class CounterPage extends ConsumerWidget {
  const CounterPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('Riverpod Counter')),
      body: Center(child: Text('Count: $count')),
      floatingActionButton: FloatingActionButton(
        onPressed: () =>
            ref.read(counterProvider.notifier).increment(),
        child: const Icon(Icons.add),
      ),
    );
  }
}
  • ref.watch(counterProvider) subscribes to state and rebuilds the consumer when it changes.
  • ref.read(counterProvider.notifier) obtains the notifier to call a command without listening to it.
  • state is the value managed by the notifier.

Use watch to render reactive data and read in callbacks to perform actions. Avoid using read in place of watch for values that must update the UI automatically.

5. Use Provider for derived or read-only values

Not every provider needs mutable state. A regular Provider is useful for a derived value, configuration object, or service:

final firstNameProvider = Provider<String>((ref) => 'Ava');

final greetingProvider = Provider<String>((ref) {
  final name = ref.watch(firstNameProvider);
  return 'Hello, $name!';
});

A consumer can watch greetingProvider and display the resulting string. If a dependency changes, Riverpod recalculates the dependent provider as needed.

For small mutable values, choose a state holder supported by your installed Riverpod version. APIs have evolved across major releases, so consult the version-specific documentation instead of copying declarations from mixed-version examples.

6. Fetch API data with FutureProvider

FutureProvider exposes asynchronous results as an AsyncValue, allowing the UI to render loading, data, and error states. Here is a self-contained example:

import 'package:flutter_riverpod/flutter_riverpod.dart';

final userNameProvider = FutureProvider<String>((ref) async {
  // Replace this with a repository/API call in a real app.
  await Future<void>.delayed(const Duration(milliseconds: 500));
  return 'Ava Patel';
});

Render the result in a consumer widget:

class UserNamePage extends ConsumerWidget {
  const UserNamePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userNameAsync = ref.watch(userNameProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('User')),
      body: Center(
        child: userNameAsync.when(
          loading: () => const CircularProgressIndicator(),
          error: (error, stackTrace) => const Text(
            'Could not load user. Please try again.',
          ),
          data: (name) => Text('Welcome, $name'),
        ),
      ),
    );
  }
}

when() makes the three common UI states explicit. In a real app, keep HTTP requests in a repository or service rather than embedding networking details in a widget. Avoid showing raw server errors or stack traces to users; log diagnostic details appropriately and display a helpful message.

7. Model API state and user actions with AsyncNotifier

When a feature needs asynchronous loading and commands—such as refreshing a profile or submitting a form—an AsyncNotifier can keep related behavior together. This simplified pattern uses Riverpod 2-style APIs:

import 'package:flutter_riverpod/flutter_riverpod.dart';

class Profile {
  const Profile({required this.name});
  final String name;
}

class ProfileController extends AsyncNotifier<Profile> {
  @override
  Future<Profile> build() async {
    return _fetchProfile();
  }

  Future<Profile> _fetchProfile() async {
    // Replace with a repository call.
    await Future<void>.delayed(const Duration(milliseconds: 300));
    return const Profile(name: 'Ava Patel');
  }

  Future<void> refreshProfile() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_fetchProfile);
  }
}

final profileProvider =
    AsyncNotifierProvider<ProfileController, Profile>(
  ProfileController.new,
);

Watch profileProvider in a ConsumerWidget and use when() to render loading, error, and data states. A refresh button can call ref.read(profileProvider.notifier).refreshProfile().

In production, decide whether refreshing should replace existing data with a full-screen loading state or keep previous data visible. Also handle duplicate submissions, authentication expiry, and repository errors according to your app’s requirements.

8. Separate UI, state, and data layers

Riverpod works well with layered or feature-first architecture. Widgets focus on presentation, notifiers coordinate state transitions, and repositories handle data access.

UI Layer — Flutter widgets

Watches state · sends user actions

↕
State / Application Layer — Notifier

Coordinates use cases · exposes state

↕
Data Layer — Repository / API / Local storage

This is one useful architecture, not a requirement that every app must use exactly three layers.

Example feature-first structure:

lib/
  core/
    network/
    errors/
  features/
    profile/
      data/
        profile_repository.dart
      application/
        profile_controller.dart
      presentation/
        profile_page.dart
      domain/
        profile.dart

Small apps do not need every folder or layer. Add abstraction when it clarifies responsibility or improves testability; avoid creating empty layers solely to follow a template.

9. Test Riverpod providers

Provider-based logic can be tested without pumping a full UI. Create a ProviderContainer, read the provider, and dispose of the container after the test:

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:your_app/counter_provider.dart';

void main() {
  test('counter starts at zero and can increment', () {
    final container = ProviderContainer();
    addTearDown(container.dispose);

    expect(container.read(counterProvider), 0);

    container.read(counterProvider.notifier).increment();

    expect(container.read(counterProvider), 1);
  });
}

Replace your_app with your package name. For providers that depend on other providers, override dependencies with fake implementations. Widget tests can wrap the widget under test in ProviderScope and use overrides to provide controlled data.

Keep tests focused on initial state, successful operations, failures, and relevant edge cases. Provider-container APIs and asynchronous test patterns can vary by Riverpod version, so consult the docs for your installed version.

10. Riverpod best practices

  • Choose the smallest suitable provider: use a simple provider for derived values and a notifier for state-changing commands.
  • Keep widgets lean: put business rules in testable classes instead of large build() methods.
  • Watch narrowly: watch only the state a widget needs. Consider select() when observing a specific property can avoid unnecessary rebuilds.
  • Use repositories for I/O: keep HTTP and database details out of presentation widgets.
  • Handle async states: account for loading, errors, empty results, and successful data.
  • Use ref.read for commands: trigger actions in callbacks without creating an unnecessary subscription.
  • Understand provider lifecycles: align auto-dispose and caching behavior with the feature’s needs.
  • Test through overrides: inject fake repositories or services rather than relying on production endpoints.
  • Prefer immutable state: replace values instead of silently mutating collections consumers depend on.
  • Follow version-specific docs: avoid mixing examples from different Riverpod major versions.

11. Common mistakes to avoid

MistakeBetter approach
Using read for values that must update the UIUse watch in the build method for reactive values.
Putting HTTP requests directly in widgetsMove data access to a repository and expose it through providers.
Ignoring error statesRender an appropriate message and a retry action where useful.
Creating too many layers for a tiny featureStart simple and add structure when it improves clarity or testing.
Mixing Riverpod major-version examplesCheck your installed version and migration notes before adopting an API.

12. When should you choose Riverpod?

Riverpod is worth considering when you need shared application state, clean dependency injection, asynchronous data handling, and testable business logic. It can be useful in apps that use repositories, feature modules, and layered architecture.

For a tiny screen, setState() may be enough. For a team that already has a consistent BLoC architecture, replacing it with Riverpod may not justify the migration cost. Choose a solution the team understands and can apply consistently.

Conclusion

Riverpod provides a structured way to manage state and dependencies in Flutter. Start with a simple provider, learn how ref.watch and ref.read differ, use Notifier for state-changing commands, and use asynchronous providers to represent loading, data, and error states. As the app grows, place data access in repositories and test state logic independently from the UI.

Keep the design proportional to the feature, use the documentation for your installed Riverpod version, and prioritize maintainable behavior over adding abstractions without a clear purpose.

Comments

Popular posts from this blog

Designing and Building Dual-Screen Apps for Concept "iPhone Duo" in Flutter

FLUTTER • ADAPTIVE UI • CONCEPT DESIGN Designing and Building Dual-Screen Apps for the Concept “iPhone Duo” in Flutter Explore adaptive layouts, two-pane navigation, simulated dual-screen experiences, and the engineering decisions behind apps designed for two displays. Reading time: 10–12 minutes Concept disclaimer: “iPhone Duo” is used here as a hypothetical dual-screen device concept, not as a claim that Apple has announced or released such a product. Flutter examples in this article demonstrate adaptive and simulated two-pane layouts that can be tested on existing devices. What if an iPhone could provide two displays that work together? Imagine reading an article on one screen while keeping notes on the other, browsing a product list beside its details, or viewing a video while controlling playback on a separate panel. This kind of experience introduces an interesting app-design challenge: the interface must understand how much space is avail...

Dynamic and responsive ListView in flutter

How to create responsive and dynamic Listview? Step 1: Create Listview builder ListView.builder( physics: ScrollPhysics(parent: AlwaysScrollableScrollPhysics()), itemCount: allBillList[ 0 ].data!.length, scrollDirection: Axis.vertical, itemBuilder: (c, index1) { String data = mainList![index1]; return ListItem(data); }) Step 2: Create separate ListItem.dart file import 'package:flutter/cupertino.dart' ; import 'package:flutter/material.dart' ; class ListItem extends StatefulWidget { ListItem({ this .data}); final String? data; @override _ListItemState createState() => _ListItemState(); } class _ListItemState extends State<ListItem> { @override Widget build(BuildContext context) { // TODO: implement build return Column( children: [ Container(margin: const EdgeInsets.all( 16.0 ), child:Text(data)), BasicWidget.getDivider(), ], ); } } So if you want to delete or add items in main...

Flutter Bloc Pattern 9.1.1 Call API

Flutter Architecture Tutorial How to Fetch API Data & Display in ListView Using Flutter BLoC Pattern Build a clean Flutter app that fetches users from a REST API, manages loading and error states with BLoC, and displays results in a ListView. Fetching data from a REST API and displaying it in a scrolling list is one of the most common tasks in Flutter development. As an app grows, keeping network requests, UI code, and state management mixed together can make the code difficult to test and maintain. The BLoC (Business Logic Component) pattern helps separate business logic from the presentation layer. In this tutorial, we’ll build a small example using flutter_bloc , http , and a public sample API. You’ll learn how to handle loading, success, empty, and error states without placing API logic directly inside the widget. What we’ll build Fetch a list of users from a REST endpoint Create a model, repository, BLoC, events, and st...

Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane

Flutter Tutorial Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane Learn how to adapt your Flutter layout for dual-screen and foldable devices using Microsoft's dual_screen package and Flutter's TwoPane widget. Dual-screen and foldable mobile devices offer unique screen real estate. Instead of showing a single list view that navigates to a new page, dual-screen layouts allow developers to display a Master-Detail view side-by-side when unfolded or on dual screens, and fall back to a single page view on standard phones. What You Will Learn: Understanding Dual-Screen Hinge and Folding Display Features Implementing the TwoPane widget for responsive multi-screen layouts Handling Master-Detail state selection dynamically Material 3 visual layout standards for adaptive design 1. Step 1: Add Dependencies Add the official dual_screen ...

A Complete Guide to Publishing a Flutter App on the Apple App Store

Flutter • iOS • App Store Connect A Complete Guide to Publishing a Flutter App on the Apple App Store From your first iOS release build to TestFlight, App Review, and a successful App Store launch. Who is this guide for? Flutter developers who have an app ready for iOS distribution. You need a Mac with a compatible version of Xcode and access to the Apple Developer Program. Apple requirements change, so verify current policies before submitting. Publishing workflow at a glance 👤 1. Account Developer Program ⚙️ 2. Configure Bundle ID and signing 📦 3. Build Archive and upload 🚀 4. Release Review and launch 1. Prerequisites Mac and Xcode: iOS builds and signing require macOS and Xcode. Use versions supported by your Flutter SDK and accepted by App Store Connect. Flutter SDK: Use a stable release and check that your plugins support the target iOS version. Apple Developer Program: Enroll if you need App Store distribution. Membership terms and fees depend on your r...
  Implementing Search by Character in Flutter: A Complete Guide with Examples Searching is one of the most common features in mobile applications. Whether you're building a contact list, product catalog, employee directory, or chat application, users expect search results to update instantly as they type. Flutter makes it easy to implement search by character , where the list filters after every keystroke without requiring users to tap a search button. In this guide, you'll learn how to implement a fast, efficient, and scalable character-by-character search in Flutter. What is Search by Character? Search by character (also called live search or incremental search ) filters data every time the user types a new character. For example: User Types Results ---------------------------------------- A Apple, Amazon, Adobe Ap Apple App Apple Appl Apple Apple Apple Instead of waiting for the user to...

How to Write Test Cases in Flutter: A Complete Guide with Examples

Flutter Testing Handbook How to Write Test Cases in Flutter: A Complete Guide with Examples Learn how to write unit, widget, and integration tests in Flutter—with practical Dart examples, testable app structure, and commands you can use in your project. Testing helps you catch bugs early, protect existing features when code changes, and ship Flutter apps with greater confidence. Instead of manually checking every screen after each update, you can automate many checks and run them whenever you change your code. In this guide, we’ll cover the main Flutter testing types, set up a test environment, write examples for business logic and UI, test asynchronous behavior, mock dependencies, and run tests from the command line. What you’ll learn How unit, widget, and integration tests differ How to create and run a Flutter test file How to test validation, calculations, buttons, and displayed text How to handle asynchronous ...

Learn SQLite using flutter

What Is SQLite SQLite is an open source relational database, it is used to create a database, perform different operation like add, delete and remove data. SQLite setup Add the required dependencies. For this article, you’ll need the  sqflite package  for using the SQLite database. Open a simulator device or connect a real device to your system and start the app using the following command: flutter run Add your SQLite file which you want to read and write. Place your file under assets folder like below image Create DBQueries and DBProvider. DBProvider is require to connect your app with database. import 'dart:io' ; import 'package:flutter/services.dart' ; import 'package:path_provider/path_provider.dart' ; import 'package:sqflite/sqflite.dart' ; import 'package:path/path.dart' ; class DBProvider { static final DBProvider _instance = new DBProvider . internal (); factory DBProvider() => _instance ; static Database _database ; Future<...

Manage Firebase storage using flutter

Flutter • Firebase • Mobile Development Manage Firebase Storage Using Flutter A practical, end-to-end guide to uploading, monitoring, listing, downloading, and deleting files securely with Cloud Storage for Firebase. Beginner friendly Working code examples Security rules What you will build: a small Flutter file manager that uploads a selected file, shows upload progress, retrieves its download URL, lists files in a user folder, and deletes a selected file. The examples assume Firebase Authentication is enabled and the user is signed in. 1. What is Firebase Storage? Cloud Storage for Firebase stores user-generated content such as profile pictures, receipts, PDFs, videos, and documents. Flutter communicates with the Firebase Storage SDK; the SDK sends the file to a storage bucket, where Firebase Security Rules decide whether the request is allowed. 📱 Flutter app Selects the file → 🔐 Firebase SDK Checks request access ...

Customised Flutter AppBar

Create centralized AppBar for all screens at one place. In just 2 steps you create your own appBar. 1) Create AppBar.dart here you have to pass true and false to showRight and inside rightWidget pass widget from parent screen.(check step 2) class  AppBarWidget { static getAppBar (String title, [showRight, rightWidget]) { if (showRight == null ) { showRight = false ; } return AppBar ( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. backgroundColor: Colors. white , title: Text ( title, style: TextStyle (color: AppColors. btn_primary_dark_new ,fontWeight: FontWeight. w600 ), ), centerTitle: true , leadingWidth: 100 , leading: Padding ( padding: const EdgeInsetsDirectional . only (start: 8.0 ), child: InkWell ( onTap: () { Get.back(); }, child: Row ( ...