-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.dart
86 lines (74 loc) · 2.17 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
// create a cubix
import 'package:cubix/cubix.dart';
import 'package:cubix/cubix_widgets.dart';
import 'package:flutter/material.dart';
class CounterCubix extends Cubix<int> {
CounterCubix() : super(0);
// method base action
void increment() => state++;
@override
onDispatch(ActionBase action) {
// log an action dispatching
// cannot track method base actions (increment)
// ignore: avoid_print
print(action.runtimeType.toString());
}
}
// class base action
// using SyncAction for sync code
class DecrementAction extends SyncAction<void, int> {
final int step;
DecrementAction([this.step = 1]);
@override
body() {
// update state
state -= step;
}
}
class DecrementAsyncAction extends AsyncAction<void, int> {
final int step;
DecrementAsyncAction([this.step = 1]);
@override
body() async {
// delay in 2 seconds
await Future.delayed(const Duration(seconds: 2));
// perform increment by dispatch another action
dispatch(DecrementAction(step));
}
}
void main() => runApp(const App());
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
build(context) {
return CubixProvider(
// build widget from CounterCubix
// the builder receives BuildContext and Cubix objects
child: CounterCubix.new.build(
(context, cubix) {
return Column(
children: [
// getting state of cubix
Text(cubix.state.toString()),
ElevatedButton(
// resolve cubix from context object
onPressed: context.cubix(CounterCubix.new).increment,
child: const Text('Increment'),
),
ElevatedButton(
// dispatch class base action
onPressed: () => cubix.dispatch(DecrementAction()),
child: const Text('Decrement'),
),
ElevatedButton(
// dispatch class base action with args
onPressed: () => cubix.dispatch(DecrementAsyncAction(2)),
child: const Text('Decrement Async'),
)
],
);
},
),
);
}
}