Last active
June 20, 2021 15:51
-
-
Save kranfix/59c2b02fad092327357e728d79d31e65 to your computer and use it in GitHub Desktop.
Tip for prepare your Flutter app for the new WidgetReference in RiverPod
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
/// Temporal file for migrating to [WidgetRef] syntax in the | |
/// becoming `riverpod` version. | |
/// | |
/// See the new RFC and the implementation (WIP) | |
/// - RFC: https://github.com/rrousselGit/river_pod/issues/335 | |
/// - PR: https://github.com/rrousselGit/river_pod/pull/462 | |
/// | |
/// Medum article about the usage: https://link.medium.com/4F5gdDISXfb | |
library temporal_widget_ref_migration; | |
import 'package:flutter/widgets.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
import 'package:hooks_riverpod/hooks_riverpod.dart' | |
show BuildContextX, RootProvider, ProviderListenable, useProvider; | |
import 'package:hooks_riverpod/hooks_riverpod.dart' as hr; | |
export 'package:hooks_riverpod/hooks_riverpod.dart' | |
hide BuildContextX, RootProvider, ProviderListenable, useProvider; | |
typedef ConsumerBuilder = Widget Function(BuildContext, WidgetRef, Widget?); | |
mixin WidgetRef on State<ConsumerWidget> { | |
final T Function<T>(ProviderListenable<T>) watch = useProvider; | |
T read<T>(RootProvider<Object?, T> provider) => context.read(provider); | |
Created refresh<Created>(RootProvider<Created, Object> provider) { | |
return context.refresh(provider); | |
} | |
} | |
abstract class ConsumerWidget extends StatefulHookWidget { | |
const ConsumerWidget({Key? key}) : super(key: key); | |
Widget build(BuildContext context, WidgetRef ref); | |
@override | |
_ConsumerState createState() => _ConsumerState(); | |
} | |
class _ConsumerState extends State<ConsumerWidget> with WidgetRef { | |
@override | |
Widget build(context) => widget.build(context, this); | |
} | |
abstract class HookConsumerWidget extends ConsumerWidget { | |
const HookConsumerWidget({Key? key}) : super(key: key); | |
} | |
class Consumer extends ConsumerWidget { | |
const Consumer({Key? key, required this.builder, this.child}) | |
: super(key: key); | |
final ConsumerBuilder builder; | |
final Widget? child; | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return builder(context, ref, child); | |
} | |
} | |
class HookConsumer extends ConsumerWidget { | |
const HookConsumer({Key? key, required this.builder, this.child}) | |
: super(key: key); | |
final ConsumerBuilder builder; | |
final Widget? child; | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return builder(context, ref, child); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment