-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.dart
More file actions
277 lines (256 loc) · 8.22 KB
/
main.dart
File metadata and controls
277 lines (256 loc) · 8.22 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import 'dart:async';
import 'package:control/control.dart';
import 'package:flutter/material.dart';
import 'package:l/l.dart';
/// Observer for [Controller], react to changes in the any controller.
final class ControllerObserver implements IControllerObserver {
const ControllerObserver();
@override
void onCreate(Controller controller) {
l.v6('Controller | ${controller.name}.new');
}
@override
void onDispose(Controller controller) {
l.v5('Controller | ${controller.name}.dispose');
}
@override
void onHandler(HandlerContext context) {
final stopwatch = Stopwatch()..start();
l.d(
'Controller | '
'${context.controller.name}.${context.name}',
context.meta,
);
context.done.whenComplete(() {
stopwatch.stop();
l.d(
'Controller | '
'${context.controller.name}.${context.name} | '
'duration: ${stopwatch.elapsed}',
context.meta,
);
});
}
@override
void onStateChanged<S extends Object>(
StateController<S> controller,
S prevState,
S nextState,
) {
final context = Controller.context;
if (context == null) {
// State change occurred outside of the handler
l.d(
'StateController | '
'${controller.name} | '
'$prevState -> $nextState',
);
} else {
// State change occurred inside the handler
l.d(
'StateController | '
'${controller.name}.${context.name} | '
'$prevState -> $nextState',
context.meta,
);
}
}
@override
void onError(Controller controller, Object error, StackTrace stackTrace) {
final context = Controller.context;
if (context == null) {
// Error occurred outside of the handler
l.w(
'Controller | '
'${controller.name} | '
'$error',
stackTrace,
);
} else {
// Error occurred inside the handler
l.w(
'Controller | '
'${controller.name}.${context.name} | '
'$error',
stackTrace,
context.meta,
);
}
}
}
void main() => runZonedGuarded<Future<void>>(() async {
// Setup controller observer
Controller.observer = const ControllerObserver();
runApp(const App());
}, (error, stackTrace) => l.e('Top level exception: $error', stackTrace));
/// Counter state for [CounterController]
typedef CounterState = ({int count, bool idle});
/// Counter controller with sequential handler
class CounterController extends StateController<CounterState>
with SequentialControllerHandler {
/// Creates a [CounterController] with an optional initial state.
CounterController({CounterState? initialState})
: super(initialState: initialState ?? (idle: true, count: 0));
/// Adds a value to the current count.
Future<int?> add(
int value, {
void Function(int result)? onSuccess,
void Function(Object error, StackTrace stackTrace)? onError,
}) => handle<int>(
() async {
setState((idle: false, count: state.count));
final result = await Future<int>.delayed(
const Duration(milliseconds: 1500),
() => state.count + value,
);
setState((idle: true, count: result));
onSuccess?.call(result);
return result;
},
error: (error, stackTrace) async {
onError?.call(error, stackTrace);
},
done: () async {},
name: 'add',
meta: {'operation': 'add', 'value': value},
);
/// Subtracts a value from the current count.
Future<int?> subtract(
int value, {
void Function(int result)? onSuccess,
void Function(Object error, StackTrace stackTrace)? onError,
}) => handle<int>(
() async {
setState((idle: false, count: state.count));
final result = await Future<int>.delayed(
const Duration(milliseconds: 1500),
() => state.count - value,
);
onSuccess?.call(result);
setState((idle: true, count: result));
return result;
},
error: (error, stackTrace) async {
onError?.call(error, stackTrace);
},
done: () async {},
name: 'subtract',
meta: {'operation': 'subtract', 'value': value},
);
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'StateController example',
theme: ThemeData.dark(),
home: const CounterScreen(),
builder: (context, child) =>
// Create and inject the controller into the element tree.
ControllerScope<CounterController>(CounterController.new, child: child),
);
}
class CounterScreen extends StatelessWidget {
const CounterScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Counter')),
floatingActionButton: const CounterScreen$Buttons(),
body: const SafeArea(child: Center(child: CounterScreen$Text())),
);
}
class CounterScreen$Text extends StatelessWidget {
const CounterScreen$Text({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme.headlineMedium;
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Count: ', style: style),
SizedBox.square(
dimension: 64,
child: Center(
// Receive CounterController from the element tree
// and rebuild the widget when the state changes.
child: StateConsumer<CounterController, CounterState>(
buildWhen: (previous, current) =>
previous.count != current.count ||
previous.idle != current.idle,
builder: (context, state, _) {
final text = state.count.toString();
return AnimatedSwitcher(
duration: const Duration(milliseconds: 500),
transitionBuilder: (child, animation) => ScaleTransition(
scale: animation,
child: FadeTransition(opacity: animation, child: child),
),
child: state.idle
? Text(text, style: style, overflow: TextOverflow.fade)
: const CircularProgressIndicator(),
);
},
),
),
),
],
);
}
}
class CounterScreen$Buttons extends StatelessWidget {
const CounterScreen$Buttons({super.key});
/// Show a message using a [SnackBar].
static void showMessage(BuildContext context, String message) {
if (!context.mounted) return;
ScaffoldMessenger.maybeOf(context)
?..clearSnackBars()
..showSnackBar(
SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
);
}
@override
Widget build(BuildContext context) => ValueListenableBuilder<bool>(
// Transform [StateController] in to [ValueListenable]
valueListenable: context.controllerOf<CounterController>().select(
(state) => state.idle,
),
builder: (context, idle, _) => IgnorePointer(
ignoring: !idle,
child: AnimatedOpacity(
duration: const Duration(milliseconds: 350),
opacity: idle ? 1 : .25,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FloatingActionButton(
key: ValueKey('add#${idle ? 'enabled' : 'disabled'}'),
onPressed: idle
? () => context.controllerOf<CounterController>().add(
1,
onSuccess: (result) =>
showMessage(context, 'Result: $result'),
)
: null,
child: const Icon(Icons.add),
),
const SizedBox(height: 8),
FloatingActionButton(
key: ValueKey('subtract#${idle ? 'enabled' : 'disabled'}'),
onPressed: idle
? () => context.controllerOf<CounterController>().subtract(
1,
onSuccess: (result) =>
showMessage(context, 'Result: $result'),
)
: null,
child: const Icon(Icons.remove),
),
],
),
),
),
);
}