Comprehensive Guide to Riverpod: From Basics to Advanced Usage in Flutter
This article provides an in‑depth tutorial on Riverpod for Flutter, covering its differences from Provider, step‑by‑step setup, core concepts, various Provider types, state management techniques, async handling, code generation, and advanced patterns such as side effects, request merging, and lifecycle control.
1. Provider vs Riverpod
Both libraries are authored by Remi Rousselet; Riverpod is a refactored, more powerful version of Provider that eliminates BuildContext dependency, key management, and global state limitations.
2. Basic Usage
2.1 Adding Dependencies
Install the required packages via flutter pub add flutter_riverpod and related annotation, lint, and generator packages, or add them manually to pubspec.yaml and run flutter pub get .
2.2 Code Snippet
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final clickCountProvider = StateProvider
((ref) => 0);
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final int count = ref.watch(clickCountProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Riverpod Demo')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('点击计数:$count'),
ElevatedButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const CountPage())),
child: const Text('跳转到增加计数页面'),
),
],
),
),
),
);
}
}
class CountPage extends ConsumerWidget {
const CountPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final int count = ref.watch(clickCountProvider);
return Scaffold(
appBar: AppBar(title: const Text('增加计数')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('点击计数:$count'),
ElevatedButton(
onPressed: () => ref.read(clickCountProvider.notifier).state++,
child: const Text('点击计数+1'),
),
],
),
),
);
}
}2.3 Provider Types
Riverpod offers Provider, FutureProvider, StreamProvider, NotifierProvider, AsyncNotifierProvider, and others. StateProvider, StateNotifierProvider, and ChangeNotifierProvider are now considered legacy in favor of NotifierProvider.
3. Advanced Usage
3.1 Network Requests
Encapsulate business logic in providers; use ref.watch to trigger requests and handle loading, success, and error states via AsyncValue.when or pattern matching.
3.2 Side Effects
Implement side‑effects such as API calls or file writes inside Notifier methods, ensuring state changes remain predictable.
3.3 Parameterized Providers
Use family or annotation‑generated providers to pass arguments, remembering to make arguments const or implement operator== for proper caching.
3.4 Request Merging & Lifecycle
Combine providers by passing results as parameters, control disposal with ref.onDispose , ref.invalidate , or ref.keepAlive , and implement custom extensions for debouncing and cancellation.
3.5 Linting
Enable riverpod_lint via custom_lint and an analysis_options.yaml file to catch common mistakes and enforce best practices.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.