Sub topic 1
Why Riverpod: moving state out of the widget tree
Prerequisites
You should know Dart classes, generics, and async/await. You should also know Flutter widgets, the build method, and setState. This chapter assumes you have lifted state up to a parent widget before.
Why state leaves the widget tree
A widget's State object lives only while the widget stays in the tree. When two distant screens need the same data, you must pass it down through every widget in between. Riverpod is a state management library that stores state in providers outside the widget tree. Any widget can read a provider directly, so the data no longer travels through intermediate widgets.
ProviderScope and the provider container
A provider container is an object that stores the current value of every provider in your app. ProviderScope is a widget that creates this container. Place it at the root of the app, above MaterialApp. Any widget below it can reach the providers.
Your first provider: exposing a read-only value
A provider is a top-level variable that describes how to compute a value. The following provider always returns the same string:
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');The type argument String is the type of value the provider exposes. The function receives a ref object, which lets the provider read other providers.
Reading providers with ConsumerWidget and WidgetRef
A ConsumerWidget is a widget whose build method receives a WidgetRef named ref. Call ref.watch(provider) to read a value. The widget rebuilds when that value changes.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final greetingProvider = Provider<String>((ref) => 'Hello, Riverpod');
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final greeting = ref.watch(greetingProvider);
return MaterialApp(
home: Scaffold(body: Center(child: Text(greeting))),
);
}
}Exercise
What happens if you remove ProviderScope from main and keep the rest of the code the same?
Show answer
The app throws an error when MyApp calls ref.watch, because no provider container exists to store the value of greetingProvider.