@asmut

Ассинхронный расчет во Flutter (Redux)?

Добрый.

Не могу понять почему рассчет производится не в ассинхронном потоке, при нажатии на кнопку блокируется интерфейс.
Если несложно объясните где не прав, и как верно написать + может стоит использовать дополнительные технологии.

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),
          ),
        ]),
      ),
    );
  }
}


actions.dart
class AddAction {}

class CalculationAction{
  final int counter;

  CalculationAction(this.counter);

}


middlewares.dart
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;
}


reducers.dart
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;


app_state.dart
class AppState{

  final int counter;

  AppState({required this.counter});

}
  • Вопрос задан
  • 45 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
16 мая 2024, в 23:36
200000 руб./за проект
16 мая 2024, в 23:10
12000 руб./за проект