Riverpod: StateProvider
Part of the State Management section of Coddy's Flutter journey. Lesson 18 of 27.
A Provider holds a value that never changes. For one simple value that does change, a number, a bool, a String, use a StateProvider:
final quantityProvider = StateProvider((ref) => 1);Read it the same way: ref.watch(quantityProvider) gives the number, and the widget builds again when it changes.
To change it, get its notifier, the object that holds the value, with ref.read, and set its state:
onPressed: () {
ref.read(quantityProvider.notifier).state++;
},As in Provider, use ref.watch in build to show a value and ref.read in callbacks to change it. And changing a copy changes nothing: var n = ref.read(quantityProvider); n++; adds 1 to n, not to the provider. Only setting state does.
Challenge
EasyThe pancake order shows its quantity, but the buttons do nothing yet.
- The plus adds 1 to
quantityProvider. - The minus takes 1 away, but never below 1.
Try it yourself
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final quantityProvider = StateProvider((ref) => 1);
void main() {
runApp(const ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: OrderPage(),
);
}
}
class OrderPage extends ConsumerWidget {
const OrderPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final quantity = ref.watch(quantityProvider);
return Scaffold(
appBar: AppBar(title: const Text('Pancakes')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.remove),
onPressed: () {},
),
Text('Quantity: $quantity', style: const TextStyle(fontSize: 24)),
IconButton(
icon: const Icon(Icons.add),
onPressed: () {},
),
],
),
),
);
}
}
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