/
main_show_spinner.dart
104 lines (90 loc) · 2.89 KB
/
main_show_spinner.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
// Developed by Marcelo Glasberg (2019) https://glasberg.dev and https://github.com/marcglasberg
// For more info, see: https://pub.dartlang.org/packages/async_redux
import 'dart:async';
import 'package:async_redux/async_redux.dart';
import 'package:flutter/material.dart';
late Store<AppState> store;
/// This example shows a counter and a button.
/// When the button is tapped, the counter will increment synchronously.
void main() {
store = Store<AppState>(initialState: AppState(counter: 0, something: 0));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => StoreProvider<AppState>(
store: store,
child: const MaterialApp(home: HomePage()),
);
}
class HomePage extends StatelessWidget {
const HomePage({
super.key,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Show Spinner Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
CounterWidget(),
],
),
),
// Here we disable the button while the `WaitAndIncrementAction` action is running.
floatingActionButton: context.isWaiting(WaitAndIncrementAction)
? const FloatingActionButton(
disabledElevation: 0,
onPressed: null,
child: SizedBox(width: 25, height: 25, child: CircularProgressIndicator()))
: FloatingActionButton(
disabledElevation: 0,
onPressed: () => context.dispatch(WaitAndIncrementAction()),
child: const Icon(Icons.add),
),
);
}
}
/// This action waits for 2 seconds, then increments the counter by [amount]].
class WaitAndIncrementAction extends ReduxAction<AppState> {
@override
Future<AppState?> reduce() async {
await Future.delayed(const Duration(seconds: 2));
return AppState(
counter: state.counter + 1,
something: state.something,
);
}
}
class CounterWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
var isWaiting = context.isWaiting(WaitAndIncrementAction);
return Text(
'${context.state.counter}',
style: TextStyle(fontSize: 40, color: isWaiting ? Colors.grey[350] : Colors.black),
);
}
}
extension _BuildContextExtension on BuildContext {
AppState get state => getState<AppState>();
}
class AppState {
int counter;
int something;
AppState({
required this.counter,
required this.something,
});
@override
String toString() => 'AppState{counter: $counter}';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AppState && runtimeType == other.runtimeType && counter == other.counter;
@override
int get hashCode => counter.hashCode;
}