Skip to content

Instantly share code, notes, and snippets.

@swavkulinski
Last active February 21, 2023 20:01
Show Gist options
  • Save swavkulinski/b66526d90d3f846a6f9be944d3178d16 to your computer and use it in GitHub Desktop.
Save swavkulinski/b66526d90d3f846a6f9be944d3178d16 to your computer and use it in GitHub Desktop.
Ref.read() vs Ref.watch() in Riverpod
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
/// This sample demonstrates the difference between Ref.read() and Ref.watch()
/// This sample is broken to show that despite repoProvider is updated there is no update in the UI
// This is where our state is stored
final repoProvider = StateProvider<int>((ref) => 1);
// This provider gives the formatted string based on the state defined above
final helloStringProvider = Provider<String>((ref) {
var excl = "";
// we ref.read(repoProvider) here so it always the first value
final r = ref.read(repoProvider);
for(var i = 0; i < r; i++){
excl = "$excl!";
}
debugPrint('myStringProvider()');
return "Hello World $excl";
});
// This provider handles the user input
final handleFabProvider = Provider<VoidCallback>((ref) {
return (){
final s = ref.read(repoProvider) + 1;
// despite we only read first value above, we increment and assign it back to the repoProvider
ref.read(repoProvider.notifier).state = s;
// so the value is increasing
print('State: $s');
};
});
void main() {
runApp(ProviderScope(child:MyApp()));
}
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
floatingActionButton: FloatingActionButton(
onPressed:
ref.watch(handleFabProvider),
child: const Icon(Icons.plus_one),
)
),
);
}
}
class MyWidget extends ConsumerWidget {
@override
Widget build(BuildContext context,WidgetRef ref ) {
// despite we watch here we always watch something which doesn't change
final text = ref.watch(helloStringProvider);
debugPrint('text hash: ${text.hashCode}');
return Text(
text,
style: Theme.of(context).textTheme.headlineMedium,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment