-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhooks_example.dart
More file actions
61 lines (50 loc) · 1.51 KB
/
Copy pathhooks_example.dart
File metadata and controls
61 lines (50 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import 'package:async_controller/async_controller.dart';
import 'package:example/helpers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
class HooksExamplePage extends HookWidget with ExamplePage {
Future<String> fetch() async {
await Future<void>.delayed(Duration(seconds: 1));
return 'Hello world';
}
@override
Widget build(BuildContext context) {
final loader = useNewChangeNotifier(() => AsyncController.method(fetch))!;
return Scaffold(
appBar: buildAppBar(),
body: loader.buildAsyncData(builder: (_, data) {
return Center(child: Text(data));
}),
);
}
@override
String get title => 'flutter_hooks';
}
/// Creates the provided notifier once, and then disposes it when appropriate.
T? useNewChangeNotifier<T extends ChangeNotifier>(T Function() builder) {
return use(_NewChangeNotifierHook(builder: builder));
}
class _NewChangeNotifierHook<T extends ChangeNotifier> extends Hook<T?> {
const _NewChangeNotifierHook({this.builder});
final T Function()? builder;
@override
_NewChangeNotifierHookState<T> createState() =>
_NewChangeNotifierHookState<T>();
}
class _NewChangeNotifierHookState<T extends ChangeNotifier>
extends HookState<T?, _NewChangeNotifierHook<T>> {
T? notifier;
@override
void initHook() {
super.initHook();
notifier = hook.builder!();
}
@override
T? build(BuildContext context) {
return notifier;
}
@override
void dispose() {
notifier!.dispose();
}
}