简体   繁体   English

Flutter 块状态未正确更新

[英]Flutter bloc state does not update properly

I'm experiencing an issue, that my state isn't updating and I can't find the problem in my code.我遇到了一个问题,我的状态没有更新,我在我的代码中找不到问题。

Basically I'm updating my state like this :基本上我正在像这样更新我的状态:

Bloc集团

  @override
  WorkoutState get initialState => WorkoutsLoaded(
      workouts: ["Workout1", "Workout2", "Workout3"], selectedWorkoutIndex: 0);

  @override
  Stream<WorkoutState> mapEventToState(WorkoutEvent event) async* {
    if (event is UpdateWorkoutPageIndex) {
      yield* _mapUpdateWorkoutPageIndexToState(event);
    }

    if (event is IncreaseWorkoutPageIndex) {
      yield* _mapIncreaseWorkoutPageIndexToState(event);
    }

    if (event is DecreaseWorkoutPageIndex) {
      yield* _mapDecreaseWorkoutPageIndexToState(event);
    }
  }

  Stream<WorkoutState> _mapUpdateWorkoutPageIndexToState(
      UpdateWorkoutPageIndex event) async* {
    print("_mapUpdateWorkoutPageIndexToState : " + this.state.toString());
    yield WorkoutsLoaded(
        workouts: ["Workout0", "Workout2", "Workout3"],
        selectedWorkoutIndex: event.pageIndex);
    print("_mapUpdateWorkoutPageIndexToState End : " + this.state.toString());
  }

Event事件

class UpdateWorkoutPageIndex extends WorkoutEvent {
  final int pageIndex;

  const UpdateWorkoutPageIndex({@required this.pageIndex});

  @override
  List<Object> get props => [pageIndex];

  @override
  String toString() => "UpdateWorkoutPageIndex { pageIndex: $pageIndex }";
}

State状态

class WorkoutsUninitialised extends WorkoutState {}

class WorkoutsLoaded extends WorkoutState {
  final List<String> workouts;
  final int selectedWorkoutIndex;

  const WorkoutsLoaded({
    this.workouts,
    this.selectedWorkoutIndex,
  });

  @override
  String toString() {
    return "WorkoutsLoaded : " + this.workouts.toString() + " - " + this.selectedWorkoutIndex.toString();
  }
}

The state doesn't change, even when the event.pageIndex is different.即使 event.pageIndex 不同,状态也不会改变。

I can provide further code if necessary, but currently I'm not sure what code could be needed to solve my issue.如有必要,我可以提供更多代码,但目前我不确定需要哪些代码来解决我的问题。

if your WorkoutEvent Class extends equatable , Then you need to add this line如果您的WorkoutEvent Class扩展了equatable ,那么您需要添加这一行

    List<Object> get props => [pageIndex]; 

to your UpdateWorkoutPageIndex class到您的UpdateWorkoutPageIndex

The aim is that the [List] of props (properties) will be used to determine whether two [Equatables] are equal.目的是使用props(属性)的[List]来判断两个[Equatables]是否相等。 Hence, state will be updated.因此,状态将被更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM