Menu
CoddyTech

ConsumerWidget and ref.watch

Part of the State Management section of Coddy's Flutter journey. Lesson 17 of 27.

Any widget can read a provider once it can get a ref. To give it one, change two things:

  • extends StatelessWidget becomes extends ConsumerWidget.
  • build gets a second parameter, WidgetRef ref.
class CityName extends ConsumerWidget {
  const CityName({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final city = ref.watch(cityProvider);
    return Text(city);
  }
}

ref.watch(cityProvider) gives you the provider's value, here the text Lisbon, and builds the widget again whenever that value changes. Without ref.watch, cityProvider is only the provider itself, not its value.

Each widget that needs a value asks for it like this, wherever it sits. Nothing is passed down through constructors, and nothing needs context to find it.

challenge icon

Challenge

Easy

CityName and Temperature show placeholders. Make them read the providers at the top of the file:

  • Turn both into ConsumerWidgets.
  • CityName shows the value of cityProvider.
  • Temperature shows the value of temperatureProvider followed by °C, at the same size.

Try it yourself

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

final cityProvider = Provider((ref) => 'Lisbon');
final temperatureProvider = Provider((ref) => 21);

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const CityName()),
        body: const Center(child: Temperature()),
      ),
    );
  }
}

class CityName extends StatelessWidget {
  const CityName({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('City');
  }
}

class Temperature extends StatelessWidget {
  const Temperature({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('0°C', style: TextStyle(fontSize: 64));
  }
}
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