Skip to content

Instantly share code, notes, and snippets.

@FantasyCheese
Last active February 4, 2022 10:14
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,
);
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment