Flutter - Riverpod

July 27, 2022
cgrant

Flutter - Riverpod

Riverpod is a reactive caching and data-binding framework for Flutter and Dart applications. It’s designed to solve the problems of provider while being more robust and testable.

Key Concepts

Provider: A wrapper around a value that makes it observable and allows widgets to listen to changes.

Consumer: A widget that listens to providers and rebuilds when they change.

Ref: An object that allows providers to interact with other providers and manage their lifecycle.

Basic Setup

Add the dependency to your pubspec.yaml:

dependencies:
  flutter_riverpod: ^2.4.9

Wrap your app with ProviderScope:

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

Simple Provider Example

// Create a provider
final counterProvider = StateProvider<int>((ref) => 0);

// Use in a widget
class CounterWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);
    
    return Column(
      children: [
        Text('Count: $count'),
        ElevatedButton(
          onPressed: () => ref.read(counterProvider.notifier).state++,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
References
  • Flutter State Management
  • Provider Pattern