0

BLoC (cubit) を使用してフラッターで非同期カウンター アプリを作成しています。ローディング状態を発行すると、カウンターがインクリメントせずに 0 に戻ります。この問題を解決するにはどうすればよいですか?

コード:

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';

part 'counter_state.dart';
class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(Counter(counter: 0));

  void increment() {
    print('before CounterLoading() ${state.counter}');
    emit(CounterLoading());
    print('after CounterLoading() ${state.counter}');

    Timer(Duration(seconds: 2), () {
      emit(CounterLoaded());
      print('enter code hereprevious  state ${state.counter}');
      emit(Counter(counter: state.counter + 1));
      print('next state ${state.counter}');
    });
  }
}

part of 'counter_cubit.dart';

@immutable
abstract class CounterState {
  final int counter = 0;
}

class Counter extends CounterState {
  final int counter;
    
  Counter({this.counter});
}

class CounterLoading extends CounterState {
  CounterLoading();
}

class CounterLoaded extends CounterState {
  CounterLoaded();
}
4

1 に答える 1

0

counter問題は、他の状態に値を持つコンストラクターが含まれていないことです。その結果、抽象クラス - 0 からデフォルト値が使用されます。状態を維持するには、すべての状態でカウンター値を設定する必要があります。作り直された状態コードは次のとおりです。

@immutable
abstract class CounterState {
  final int counter;
  
  CounterState({this.counter = 0});
}

class Counter extends CounterState {
  // you do not need the counter property here, it is defined in the base class    
    
  Counter({required int counter}) : super(counter: counter);
}

class CounterLoading extends CounterState {
  CounterLoading({required int counter}) : super(counter: counter);
}

class CounterLoaded extends CounterState {
  CounterLoaded({required int counter}) : super(counter: counter);
}

それに応じてキュビットを調整します。

class CounterCubit extends Cubit<CounterState> {
  CounterCubit() : super(Counter(counter: 0));

  void increment() {
    print('before CounterLoading() ${state.counter}');
    emit(CounterLoading(counter: state.counter));
    print('after CounterLoading() ${state.counter}');

    Timer(Duration(seconds: 2), () {
      emit(CounterLoaded(counter: state.counter));
      print('enter code hereprevious  state ${state.counter}');
      emit(Counter(counter: state.counter + 1));
      print('next state ${state.counter}');
    });
  }
}
于 2021-05-23T19:27:58.313 に答える