31.51 Flutter Package: riverpod Watch and Read

20231026

The following will tell this widget that it need to be rebuilt if the value of the counter changes.

final String count = ref.watch(counterProvider);
import 'package:flutter_riverpod/flutter_riverpod.dart';

...

void main() {
  runApp(
    // Adding ProviderScope enables Riverpod for the entire project.
    const ProviderScope(child: MyApp()),
  );
}

...

/// Providers are declared globally and specify how to create a state.
final counterProvider = StateProvider((ref) => 0);

...

class MyHomePage extends ConsumerWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(

      ...
        
            Consumer(
              builder: (context, ref, _) {
                // The watch method will read a provider and listen to it.
                final count = ref.watch(counterProvider);
                return Text(
                  '$count',
                  key: const Key('counterState'),
                  style: Theme.of(context).textTheme.headlineMedium,
                );
              },
            ),

      ...

      floatingActionButton: FloatingActionButton(
        key: const Key('increment_floatingActionButton'),
        // The read method will read a provider without listening to it.
        onPressed: () => ref.read(counterProvider.notifier).state++,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),

...
    );
  }
}


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0