-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
86 lines (73 loc) · 2.15 KB
/
main.dart
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import 'package:async_redux/async_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_hooks/flutter_hooks.dart' hide Store;
import 'package:flutter_hooks_async_redux/flutter_hooks_async_redux.dart';
class AppState {
final int counter;
const AppState({this.counter = 0});
}
T useAppState<T>(T Function(AppState state) converter, {bool distinct = true}) =>
useSelector<AppState, T>(converter, distinct: distinct);
void main() {
runApp(
MaterialApp(
home: StoreProvider<AppState>(
store: Store<AppState>(initialState: const AppState()),
child: const Application(),
),
),
);
}
class Application extends HookWidget {
const Application({super.key});
@override
Widget build(BuildContext context) {
final dispatch = useDispatch();
int counter = useAppState((state) => state.counter);
var isWaitingIncrement = useIsWaiting(IncrementAction);
useEffect(() {
dispatch(SetCounter(42));
}, []);
return Scaffold(
body: Center(
child: Text('Counter is $counter'),
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton(
disabledElevation: 0,
onPressed: isWaitingIncrement ? null : () => dispatch(IncrementAction()),
child: isWaitingIncrement ? const CircularProgressIndicator() : const Icon(Icons.add),
),
const SizedBox(height: 12),
FloatingActionButton(
child: const Icon(Icons.clear),
onPressed: () {
dispatch(ResetCounter());
},
),
],
),
);
}
}
class IncrementAction extends ReduxAction<AppState> {
@override
Future<AppState?> reduce() async {
await Future.delayed(const Duration(milliseconds: 500));
return AppState(counter: state.counter + 1);
}
}
class SetCounter extends ReduxAction<AppState> {
final int value;
SetCounter(this.value);
@override
AppState reduce() => AppState(counter: value);
}
class ResetCounter extends ReduxAction<AppState> {
@override
AppState reduce() {
return const AppState();
}
}