Last active
February 4, 2022 10:14
-
-
Save FantasyCheese/e50225e3d2f315a5223bbf25774dd3bd to your computer and use it in GitHub Desktop.
Simplest Riverpod Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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