Created with <3 with dartpad.dev.
Created
November 26, 2023 21:20
-
-
Save knaeckeKami/ba69a9c1066bed38ea72ec8dd185f44d to your computer and use it in GitHub Desktop.
iridescent-tundra-1306
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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
import 'package:hooks_riverpod/hooks_riverpod.dart'; | |
typedef User = ({String id, String firstName, String lastName}); | |
// some future provider that holds some value | |
final userProvider = FutureProvider((ref) async { | |
await Future.delayed(const Duration(milliseconds: 200)); | |
final id = Random().nextInt(1000).toString(); | |
return (id: id, firstName: "Abigail $id", lastName: "Miller"); | |
}); | |
// a provider that may extract some value from userProvider | |
final firstNameProvider = FutureProvider((ref) { | |
return ref.watch(userProvider.selectAsync((data) => data.firstName)); | |
}); | |
// used whenData to double the value | |
// has 1 frame loading state when userProvider is invaidated and updates | |
final greetingProvider = Provider((ref) { | |
return ref | |
.watch(firstNameProvider) | |
.whenData((firstname) => "Hello $firstname!"); | |
}); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ProviderScope( | |
child: MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
final greeting = ref.watch(greetingProvider); | |
final src = ref.watch(userProvider); | |
final firstname = ref.watch(firstNameProvider); | |
print(src); | |
print(firstname); | |
print(greeting); | |
print("---"); | |
return Column( | |
children: [ | |
if(greeting.hasValue) | |
Text(greeting.value!) | |
else const CircularProgressIndicator(), | |
TextButton( | |
onPressed: () { | |
print("invalidate"); | |
ref.invalidate(userProvider); | |
}, | |
child: const Text("invalidate")), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment