Answer the question
In order to leave comments, you need to log in
Asynchronous calculation in Flutter (Redux)?
Kind.
I can not understand why the calculation is not performed in an asynchronous thread, when the button is pressed, the interface is blocked.
If it’s easy to explain where it’s wrong, and how to write correctly + it may be worth using additional technologies.
main.dart
void main() {
Store<AppState> store = Store(reducer,
middleware: [calculationMiddleware], initialState: AppState(counter: 0));
runApp(StoreProvider(store: store, child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Redux 0 (test)',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final store = StoreProvider.of<AppState>(context);
return Scaffold(
appBar: AppBar(
title: Text("What's"),
),
body: Center(
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextField(),
SizedBox(height: 50,),
StoreConnector<AppState, AppState>(
builder: (context, vm) => Text(
vm.counter.toString(),
style: TextStyle(fontSize: 35),
),
converter: (store) => store.state),
SizedBox(height: 20,),
FloatingActionButton(
onPressed: () => store.dispatch(AddAction()),
child: Icon(Icons.add),
),
]),
),
);
}
}
class AddAction {}
class CalculationAction{
final int counter;
CalculationAction(this.counter);
}
void calculationMiddleware(
Store<AppState> store, dynamic action, NextDispatcher nextDispatcher) {
if (action is AddAction) {
_calculationCounter(store.state.counter)
.then((value) => store.dispatch(CalculationAction(value)));
}
nextDispatcher(action);
}
Future<int> _calculationCounter(int counter) async {
for(var i = 0; i < 500000000; i++){
counter ++;
}
return counter;
}
AppState reducer(AppState state, dynamic action) =>
AppState(counter: _counterReducer(state.counter, action));
Reducer<int> _counterReducer = combineReducers([
TypedReducer<int, AddAction>(_addCounterReducer),
TypedReducer<int, CalculationAction>(_calculationReducer),
]);
int _addCounterReducer(int counter, AddAction action) => counter;
int _calculationReducer(int counter, CalculationAction action) => action.counter;
class AppState{
final int counter;
AppState({required this.counter});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question