Created with <3 with dartpad.dev.
Created
November 26, 2023 21:03
-
-
Save knaeckeKami/4734ac7b6f3a929ac1f79928ae8e5801 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(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 sourceProvider | |
final firstNameProvider = FutureProvider((ref) { | |
return ref.watch(userProvider.selectAsync((data) => data.firstName)); | |
}); | |
// used whenData to double the value | |
// has 1 frame loading state when sourceProvider is invaidated | |
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 CircularProgressIndicator(), | |
TextButton( | |
onPressed: () { | |
print("invalidate"); | |
ref.invalidate(userProvider); | |
}, | |
child: Text("invalidate")), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment