-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
506 lines (465 loc) · 13.4 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
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:flutter_i18n/loaders/decoders/json_decode_strategy.dart';
// ignore: depend_on_referenced_packages
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_mediator/mediator.dart';
import 'models/list_model.dart';
import 'models/my_model.dart';
import 'models/setting_model.dart';
import 'pages/info_page.dart';
import 'widgets/bottom_navigation_controller.dart';
import 'widgets/widget_extension.dart';
const double Width = 150;
final globalInt = globalWatch(1);
final globalList = globalWatch(<int>[]);
void main() {
runApp(
MultiHost.create3(
MyModel(updateMs: 1000), // model that extends Pub
ListModel(updateMs: 500), // model that extends Pub
Setting(),
child: MyApp(),
),
// MultiHost.create( // Generic form
// hosts: [
// Host<MyModel>(model: MyModel(updateMs: 1000)),
// Host<ListModel>(model: ListModel(updateMs: 500)),
// Host<Setting>(model: Setting()),
// ],
// child: MyApp(),
// ),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Mediator Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BottomNavigationWidget(
pages: navPages,
bottomNavItems: bottomNavItems,
selectedColor: Colors.amber[800]!,
backgroundColor: Colors.black54.withOpacity(0.5),
selectedIndex: 0,
),
// add flutter_i18n support
localizationsDelegates: [
FlutterI18nDelegate(
translationLoader: FileTranslationLoader(
// forcedLocale: ,
// useCountryCode: true,
// fallbackFile: 'en',
basePath: 'assets/flutter_i18n',
decodeStrategies: [JsonDecodeStrategy()],
),
missingTranslationHandler: (key, locale) {
print(
'--- Missing Key: $key, languageCode: ${locale!.languageCode}');
},
),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
);
}
}
Widget buttonPage() {
return Row(
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
allSubscriber(),
Pub.sub<MyModel>('int1AndStr1'),
//int1AndStr1Subscriber(),
fooSubscriber(),
barSubscriber(),
// inline subscriber
'bar'.subModel<MyModel>((_, model) => Text('Bar is ${model.bar}')),
starSubscriber(),
str1Subscriber(),
int1Subscriber(),
chainReactSubscriber(),
globalIntSubscriber(),
globalListSubscriber(),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
fooController(),
barController(),
bothController(),
allController(),
str1Controller(),
int1Controller(),
futureController(),
globalIntController(),
noController(),
tick1(),
tick2(),
tick3(),
],
),
],
);
}
Widget cardPage() {
//* Original form:
// return Subscriber<ListModel>(
// aspects: ListEnum.ListUpdate,
// create: (context, model) {
//* Extension form:
// return ListEnum.ListUpdate.subListModel((context, model) {
return ListEnum.ListUpdate.subModel<ListModel>((context, model) {
final data = model.data;
return GridView.builder(
itemCount: data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount:
(MediaQuery.of(context).orientation == Orientation.portrait)
? 5
: 10),
itemBuilder: (context, index) {
final item = data[index];
return Card(
color: item.color,
child: GridTile(
footer: Text(item.units.toString()),
child: Text(item.item),
).padding(const EdgeInsets.all(7.0)),
);
},
);
//* List View
// return ListView.builder(
// itemCount: data.length,
// itemBuilder: (context, index) {
// final item = data[index];
// return ListTile(
// title: Text(item.item),
// subtitle: Text(item.units.toString()),
// ).background(item.color);
// },
// );
});
}
//* Subscriber all aspects of the model
//* Get the frame aspects with `model.frameAspects`
Widget allSubscriber() {
return null.subModel<MyModel>(
(context, model) {
final aspects = model.frameAspects;
final str = aspects.isEmpty ? '' : '$aspects received';
return Text(
str,
softWrap: true,
textAlign: TextAlign.center,
);
},
).sizeBox(width: Width, height: 70);
}
//* Subscribe two aspects
Widget int1AndStr1Subscriber() {
return
// ['int1', 'star'].subModel<MyModel>(
//* Rx automatic aspect form:
rxSub<MyModel>(
(context, model) => Text(
'Int1 is ${model.int1} and Str1 is ${model.str1}',
softWrap: true,
textAlign: TextAlign.center,
),
);
}
//* Subscribe in the original form.
Widget fooSubscriber() {
return Subscriber<MyModel>(
aspects: 'foo',
create: (context, model) {
print('foo build');
return Text('Foo is ${model.foo}');
},
);
}
//* Subscriber in simple form.
Widget barSubscriber() {
return 'bar'.subModel<MyModel>((context, model) {
print('bar build');
return Text('Bar is ${model.bar}');
});
}
//* Subscriber with user extension.
Widget starSubscriber() {
return 'star'.subMyModel((context, model) {
print('star build');
return Text('Star is ${model.star}');
});
}
//* Subscriber in simple form.
Widget str1Subscriber() {
return 'str1'.subMyModel((context, model) {
print('str1 build');
return Text('Str1 is ${model.str1}');
});
}
//* Subscriber in the rx automatic aspect extension form.
Widget int1Subscriber() {
//* Original form:
// return Subscriber<MyModel>(
// aspects: 'int1',
// create:
//* Extension form:
// return 'int1'.subMyModel(
// return 'int1'.subModel<MyModel>(
//* Automatic aspect form:
return rxSub<MyModel>((_, model) => Text('Int1 is ${model.int1}'));
// //* Automatic aspect extension form:
// return (context, model) {
// print('int1 build');
// return Text('Int1 is ${model.int1.value}');
// }.rxSub<MyModel>();
}
//* Subscriber with the Global variable
Widget globalIntSubscriber() {
return globalConsume(
() => Text('Global Int: ${globalInt.value}'),
);
}
Widget globalListSubscriber() {
return globalConsume(
() => Text('Global List len: ${globalList.value.length}'),
);
// return globalList.consume(
// () => Text('Global List len: ${globalList.value.length}'),
// );
}
//* Future function for chainReactSubscriber
int httpResCounter = 0;
Future<int> _futureHttpTask() async {
await Future.delayed(const Duration(milliseconds: 0));
return ++httpResCounter;
}
//* Chain subscribe binding myModel.str1 with aspect 'chainStr1'.
Widget chainReactSubscriber() {
return 'chainStr1'.subModel<MyModel>((context, model) {
return FutureBuilder(
future: _futureHttpTask(),
initialData: httpResCounter,
builder: (BuildContext context, AsyncSnapshot snapshot) {
Widget child;
if (snapshot.hasData) {
child = Text('str1 chain counter: $httpResCounter');
} else {
child = Text('str1 init counter: $httpResCounter');
}
return Center(child: child);
},
);
});
}
//* Controller example
Widget fooController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update foo'),
onPressed: () => model.increaseFoo(),
),
);
}
//* Controller example, using fat arrow expression
Widget barController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update bar'),
onPressed: () => model.increaseBar(),
),
);
}
//* Controller example, update two variables.
Widget bothController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update both'),
onPressed: () => model.increaseBoth(),
),
);
}
//* Controller example, update all variables.
Widget allController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update all of MyModel'),
onPressed: () => model.increaseAll(),
),
);
}
Widget str1Controller() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update Str1'),
onPressed: () => model.updateStr1(),
),
);
}
Widget int1Controller() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update Int1'),
onPressed: () => model.updateInt1(),
),
);
}
Widget futureController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Future Int1:1sec'),
onPressed: () => model.futureInt1(),
),
);
}
Widget globalIntController() {
return ElevatedButton(
child: const Text('Update Global Int'),
onPressed: () {
globalInt.value++;
// A. use `.ob` to notify the host to rebuild and then return the underlying object.
globalList.ob.add(globalInt.value);
// B. get the value then notify it.
// globalList.value.add(globalInt.value);
// globalList.notify();
});
}
Widget noController() {
return Controller<MyModel>(
create: (context, model) => ElevatedButton(
child: const Text('Update none'),
onPressed: () => model.updateNone(),
),
);
}
final _ColorRegistry tick1r = _ColorRegistry();
final _ColorRegistry tick2r = _ColorRegistry();
final _ColorRegistry tick3r = _ColorRegistry();
//* rxSub tick1 with timer update
Widget tick1() {
// return 'tick1'.subMyModel(
// return 'tick1'.subModel<MyModel>(
return rxSub<MyModel>(
(context, model) {
// print('tick1 build');
return _ColoredBox(
color: tick1r.nextColor(),
child: Text('tick1 is ${model.tick1}'),
);
},
).padding(const EdgeInsets.all(5.0)).sizeBox(width: Width, height: 50);
}
//* Subscribe tick2 with timer update
Widget tick2() {
return 'tick2'
.subModel<MyModel>(
(context, model) {
// print('tick2 build');
return _ColoredBox(
color: tick2r.nextColor(),
child: Text('tick2 is ${model.tick2}'),
);
},
)
.padding(const EdgeInsets.all(5.0))
.sizeBox(width: Width, height: 50);
}
//* Subscribe tick3 with timer update
Widget tick3() {
return 'tick3'
.subModel<MyModel>(
(context, model) {
// print('tick3 build');
return _ColoredBox(
color: tick3r.nextColor(),
child: Text('tick3 is ${model.tick3}'),
);
},
)
.padding(const EdgeInsets.all(5.0))
.sizeBox(width: Width, height: 50);
}
class _ColorRegistry {
final List<Color> colors = [
Colors.pink,
Colors.red,
Colors.orange,
Colors.yellow,
Colors.lightGreen,
Colors.green,
Colors.blue,
Colors.indigo,
Colors.purple,
];
int _idx = 0;
Color nextColor() {
if (_idx >= colors.length) {
_idx = 0;
}
return colors[_idx++];
}
}
class _ColoredBox extends StatelessWidget {
const _ColoredBox({Key? key, required this.color, required this.child})
: super(key: key);
final Color color;
final Widget child;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
color: color,
child: child,
);
}
}
//* Comment out Tick1 class.
// class Tick1 extends StatelessWidget {
// final _ColorRegistry r = _ColorRegistry();
// @override
// Widget build(BuildContext context) {
// return
// // 'tick1'.subMyModel(
// rxSub<MyModel>(
// (context, model) {
// // print('tick1 build');
// return _ColoredBox(
// color: r.nextColor(),
// child: Text('tick1 is ${model.tick1}'),
// );
// },
// ).padding(const EdgeInsets.all(5.0)).sizeBox(width: Width, height: 60);
// }
// }
final bottomNavItems = [
const BottomNavigationBarItem(
label: 'Buttons',
icon: Icon(Icons.lightbulb_outline),
activeIcon: Icon(Icons.library_books),
// backgroundColor: ,
),
const BottomNavigationBarItem(
label: 'ListView',
icon: Icon(Icons.new_releases),
activeIcon: Icon(Icons.payment),
// backgroundColor: ,
),
const BottomNavigationBarItem(
label: 'Info',
icon: Icon(Icons.info_outline),
activeIcon: Icon(Icons.inbox),
// backgroundColor: ,
),
];
final navPages = [buttonPage(), cardPage(), infoPage()];