-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.dart
71 lines (53 loc) · 2.01 KB
/
index.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
import 'dart:async';
import 'package:distinctly_redux/distinctly_redux.dart';
/// A simple state object for a primitive value
class IntState {
int value;
@override
bool operator ==(dynamic other) => other is IntState && other.value == value;
@override
int get hashCode => value;
@override
String toString() => 'IntState(value: $value)';
}
// Basic actions
final String increment = 'INCREMENT';
final String decrement = 'DECREMENT';
// A reducer to increment/decrement the state accordingly
IntState reducer(IntState state, String action) {
if (action == increment) {
return new IntState()..value = state.value + 1;
} else if (action == decrement) {
return new IntState()..value = state.value - 1;
}
return state;
}
// A store reference
DistinctStore store;
// A value indicating the number of store updates
int updateCount = 0;
Future main() async {
// Create the store
store = new DistinctStore<IntState>(reducer, initialState: new IntState()..value = 0);
// Print the Store's state.
print('Value: ${store.state.value}'); // prints '0'
// Dispatch an action. This will be sent to the reducer to update the state.
store.dispatch(increment);
// Print the updated state.
print('Value: ${store.state.value}'); // prints '1'
// As an alternative, you can use the `store.onChange.listen` to respond to non-duplicate state change events.
store.onChange.listen((state) => updateCount++);
// Dispatch some actions and check the count
await dispatchAndLog(increment); // updateCount == 1
await dispatchAndLog(decrement); // updateCount == 1
await dispatchAndLog('anything'); // updateCount == 2
await dispatchAndLog('other than'); // updateCount == 2
await dispatchAndLog('inc or dec'); // updateCount == 2
await dispatchAndLog(decrement); // updateCount == 3
}
/// A helper method to dispatch [action] and log [updateCount].
Future dispatchAndLog(String action) async {
store.dispatch(action);
await new Future.delayed(new Duration());
print('Update count: $updateCount');
}