Menu
CoddyTech

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 icon

Challenge

Easy

The app stops with No ProviderScope found.

  • Wrap MyApp in a ProviderScope in main.
  • 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)),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in State Management

Practice on your own: Online Flutter compiler