Created
August 20, 2025 12:20
-
-
Save rena2019/e374d851aeb2b0b6b91a290be370e278 to your computer and use it in GitHub Desktop.
Riverpod Provider
This file contains hidden or 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/flutter_riverpod.dart'; | |
// We create a "provider", which will store a value (here "Hello world"). | |
// By using a provider, this allows us to mock/override the value exposed. | |
final helloWorldProvider = Provider((_) => 'Hello world'); | |
void main() { | |
runApp( | |
// For widgets to be able to read providers, we need to wrap the entire | |
// application in a "ProviderScope" widget. | |
// This is where the state of our providers will be stored. | |
ProviderScope( | |
child: MyApp(), | |
), | |
); | |
} | |
// Extend ConsumerWidget instead of StatelessWidget, which is exposed by Riverpod | |
class MyApp extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
final String value = ref.watch(helloWorldProvider); | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar(title: const Text('Example')), | |
body: Center( | |
child: Text(value), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment