Riverpod: ProviderScope
Part of the State Management section of Coddy's Flutter journey. Lesson 16 of 27.
Riverpod is another package for shared state, written by the same person as Provider, with some lessons learned. Its biggest change: a provider is not a widget in the tree. It is a final variable at the top of the file, outside every class:
import 'package:flutter_riverpod/flutter_riverpod.dart';
final quoteProvider = Provider((ref) => 'Small steps, every day.');The function gives the provider its value. Riverpod calls it the first time a widget asks, and keeps the result.
The values have to be kept somewhere, and that is the job of ProviderScope. It goes once, around the whole app, in main:
void main() {
runApp(const ProviderScope(child: MyApp()));
}A widget reads a provider through a ref. A ConsumerWidget is a StatelessWidget whose build gets one: ref.watch(quoteProvider). Without a ProviderScope above it, that line has nowhere to look, and the app stops with No ProviderScope found.
Challenge
EasyThe app stops with No ProviderScope found.
- Wrap
MyAppin aProviderScopeinmain. - Change the quote to
Small steps, every day.
Try it yourself
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final appNameProvider = Provider((ref) => 'Daily Quote');
final quoteProvider = Provider((ref) => 'Write your quote here.');
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends ConsumerWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final appName = ref.watch(appNameProvider);
final quote = ref.watch(quoteProvider);
return Scaffold(
appBar: AppBar(title: Text(appName)),
body: Center(
child: Text(quote, style: const TextStyle(fontSize: 24)),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in State Management
1Lifting State Up
Pass State to a ChildPass a Callback to a ChildCallbacks That Send a ValueLift State Up4Riverpod
Riverpod: ProviderScopeConsumerWidget and ref.watchRiverpod: StateProviderRiverpod: NotifierProviders That Watch ProvidersChoosing Where State LivesPractice on your own: Online Flutter compiler