Last active
September 15, 2024 09:49
-
-
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
This code and the other riverpod example need to be updated. The imports and function parameters have changed with the newest versions of riverpod.