0Pricing
Flutter Mobile Development · 课时

使用 Riverpod 管理状态

探索 Riverpod 这一可靠且便于测试的状态管理库,并了解它在复杂应用中相较其他方案的优势。

使用 Riverpod 管理状态 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Welcome to Riverpod!

Riverpod is a popular state management library for Flutter that aims to be simple, robust, and testable. It's a reimagined version of the Provider package, designed to address some of its limitations.

Think of Riverpod as a powerful toolkit for managing all the data in your app, from user settings to fetched data, in a safe and predictable way.

Riverpod's Core Strengths

Riverpod offers several key advantages:

  • Compile-time Safety: Catches errors early, before your app even runs.
  • Testability: Makes it easy to test your business logic in isolation.
  • Auto-Dispose: Providers can automatically clean up resources when no longer needed.
  • No Widget Tree Dependency: Providers don't rely on the widget tree, making them more flexible.

It helps you write cleaner, more maintainable code.

Setting Up Your App

To use Riverpod, first add the flutter_riverpod package to your pubspec.yaml. Then, wrap your entire application with a ProviderScope widget. This widget stores the state of all your providers.

Here's how to set it up:

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

void main() {
  runApp(
    // Wrap your app in a ProviderScope
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Text('Hello Riverpod'),
    );
  }
}

Introducing Providers

Providers are the core building blocks of Riverpod. They hold a piece of state and allow you to access it from anywhere in your app.

The simplest provider is a Provider, which holds an immutable value. You define it globally, making it accessible throughout your application.

import 'package:flutter_riverpod/flutter_riverpod.dart';

// A simple Provider that holds an immutable string.
final greetingProvider = Provider<String>((ref) {
  return 'Hello from Riverpod!';
});

// You can also provide numbers, objects, etc.
final counterProvider = Provider<int>((ref) => 0);

Consuming Providers with `ConsumerWidget`

To read a provider's value in your UI, you use a ConsumerWidget. This widget gives you access to a WidgetRef (often named ref), which lets you 'watch' or 'read' providers.

ref.watch() makes your widget rebuild when the provider's value changes.

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

final greetingProvider = Provider<String>((ref) {
  return 'Hello Riverpod User!';
});

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ConsumerWidget(
        builder: (context, ref, child) {
          final greeting = ref.watch(greetingProvider);
          return Scaffold(
            appBar: AppBar(title: Text('Riverpod App')),
            body: Center(child: Text(greeting)),
          );
        },
      ),
    );
  }
}

Mutable State with `StateProvider`

When you need to change a piece of state directly, use a StateProvider. It exposes a StateController, which has a state property you can modify.

This is perfect for simple UI states like a toggle or a counter.

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

// A StateProvider for a simple counter.
final counterProvider = StateProvider<int>((ref) => 0);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ConsumerWidget(
        builder: (context, ref, child) {
          final count = ref.watch(counterProvider);
          return Scaffold(
            appBar: AppBar(title: Text('Counter App')),
            body: Center(
              child: Text(
                'Count: $count',
                style: TextStyle(fontSize: 24),
              ),
            ),
            floatingActionButton: FloatingActionButton(
              onPressed: () => ref.read(counterProvider.notifier).state++,
              child: Icon(Icons.add),
            ),
          );
        },
      ),
    );
  }
}

`StateNotifierProvider` for Logic

For more complex state that involves business logic (e.g., fetching data, managing lists), you'll use a StateNotifier with StateNotifierProvider.

StateNotifier is a class you extend, and it holds your state. The provider then exposes an instance of your notifier.

import 'package:flutter_riverpod/flutter_riverpod.dart';

// 1. Define your state class (immutable recommended)
class Todo { 
  final String id; 
  final String description; 
  final bool completed; 
  Todo(this.id, this.description, this.completed); 
}

// 2. Create a StateNotifier to manage the state
class TodosNotifier extends StateNotifier<List<Todo>> {
  TodosNotifier() : super([]); // Initial state is an empty list

  void addTodo(String description) {
    state = [...state, Todo(DateTime.now().toString(), description, false)];
  }

  void toggle(String id) {
    state = [ 
      for (final todo in state) 
        if (todo.id == id) 
          Todo(todo.id, todo.description, !todo.completed) 
        else 
          todo, 
    ];
  }
}

// 3. Create the StateNotifierProvider
final todosProvider = StateNotifierProvider<TodosNotifier, List<Todo>>((ref) {
  return TodosNotifier();
});

Async Data with `FutureProvider`

Riverpod makes handling asynchronous data (like network requests) a breeze with FutureProvider and StreamProvider.

A FutureProvider exposes an AsyncValue, which gracefully handles loading, error, and data states in your UI.

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

// A FutureProvider that simulates fetching data.
final userProvider = FutureProvider<String>((ref) async {
  await Future.delayed(Duration(seconds: 2)); // Simulate network delay
  return 'John Doe';
});

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ConsumerWidget(
        builder: (context, ref, child) {
          final userAsyncValue = ref.watch(userProvider);
          return Scaffold(
            appBar: AppBar(title: Text('Async Data')),
            body: Center(
              child: userAsyncValue.when(
                loading: () => CircularProgressIndicator(),
                error: (err, stack) => Text('Error: $err'),
                data: (user) => Text('User: $user', style: TextStyle(fontSize: 24)),
              ),
            ),
          );
        },
      ),
    );
  }
}

`ref.read` vs `ref.watch`

When interacting with providers, you'll primarily use two methods on the ref object:

  • ref.watch(provider): Listens to changes in a provider. If the provider's state changes, the widget or provider watching it will rebuild/re-execute. Use this in build methods.
  • ref.read(provider): Reads a provider's current value once, without listening for future changes. Ideal for one-off actions, like button presses or initial setup.

Avoid ref.read in build methods unless you specifically don't want rebuilds.

Riverpod Provider Types

Which Riverpod provider types are best suited for managing a simple counter (a single integer that can be incremented/decremented) and for handling complex business logic with multiple actions (e.g., adding/removing items from a to-do list)?

Riverpod Recap

Great job! You've explored Riverpod, a powerful and modern state management solution for Flutter.

  • We learned about ProviderScope for app setup.
  • We used Provider for immutable data and StateProvider for simple mutable state.
  • For complex logic, StateNotifierProvider with StateNotifier is key.
  • FutureProvider helps manage async data gracefully.
  • Remember ref.watch for listening and ref.read for one-time access.

Riverpod's compile-time safety and testability make it an excellent choice for robust Flutter applications!

常见问题解答

「使用 Riverpod 管理状态」课时是免费的吗?

是的 — 「使用 Riverpod 管理状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「使用 Riverpod 管理状态」这节课中我会学到什么?

探索 Riverpod 这一可靠且便于测试的状态管理库,并了解它在复杂应用中相较其他方案的优势。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 Riverpod 管理状态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. setState 与 InheritedWidget
  2. Provider 软件包基础
  3. 使用 Riverpod 管理状态
  4. 使用流的 BLoC 模式
← 返回 Flutter Mobile Development