Created
April 27, 2025 17:56
-
-
Save fredgrott/dcf0ad8aa4ca267d4b9dcff5692b62be to your computer and use it in GitHub Desktop.
use create state notifier
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/widgets.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
import 'package:state_notifier/state_notifier.dart'; | |
typedef CreateStateNotifier<T extends StateNotifier> = T Function(); | |
/// Creates a memoized [StateNotifier] instance via [create], dispose it when | |
/// the widget disposes. | |
T useCreateStateNotifier<T extends StateNotifier>( | |
CreateStateNotifier<T> create) { | |
return use(_CreateStateNotifierHook(create)); | |
} | |
class _CreateStateNotifierHook<T extends StateNotifier> extends Hook<T> { | |
final CreateStateNotifier<T> create; | |
const _CreateStateNotifierHook(this.create); | |
@override | |
_CreateStateNotifierHookState<T> createState() => | |
_CreateStateNotifierHookState(); | |
} | |
class _CreateStateNotifierHookState<T extends StateNotifier> | |
extends HookState<T, _CreateStateNotifierHook<T>> { | |
late final T notifier = hook.create(); | |
@override | |
T build(BuildContext context) => notifier; | |
@override | |
void dispose() { | |
super.dispose(); | |
notifier.dispose(); | |
} | |
@override | |
String get debugLabel => 'useCreateStateNotifier<$T>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment