Skip to content

Instantly share code, notes, and snippets.

@FantasyCheese
Last active September 15, 2024 09:49
Show Gist options
  • Save FantasyCheese/e50225e3d2f315a5223bbf25774dd3bd to your computer and use it in GitHub Desktop.
Save FantasyCheese/e50225e3d2f315a5223bbf25774dd3bd to your computer and use it in GitHub Desktop.
Simplest Riverpod Example
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/all.dart';
final countProvider = StateProvider((ref) => 0); // declare providers anywhere
final clockProvider = StateProvider((ref) => DateTime.now());
void main() {
runApp(ProviderScope(child: MyApp())); // add ProviderScope at top level
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
context.read(countProvider).state++; // get/update state by context.read
context.read(clockProvider).state = DateTime.now();
},
child: Center(
child: Consumer( // wrap with good old consumer
builder: (context, watch, _) {
final count = watch(countProvider).state; // receive update with watch
final dateTime = watch(clockProvider).state;
return RichText(
text: TextSpan(text: "$dateTime\n$count"),
textDirection: TextDirection.ltr,
);
},
),
),
);
}
}
@nav9
Copy link

nav9 commented Sep 15, 2024

This code and the other riverpod example need to be updated. The imports and function parameters have changed with the newest versions of riverpod.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment