【问题标题】:Flutter bloc state does not update properlyFlutter bloc 状态无法正确更新
【发布时间】:2020-04-28 08:12:39
【问题描述】:

我遇到了一个问题,我的状态没有更新,我在我的代码中找不到问题。

基本上我会像这样更新我的状态:

集团

  @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());
  }

事件

class UpdateWorkoutPageIndex extends WorkoutEvent {
  final int pageIndex;

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

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

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

州

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();
  }
}

状态不会改变,即使 event.pageIndex 不同。

如有必要,我可以提供更多代码,但目前我不确定需要哪些代码来解决我的问题。

【问题讨论】:

    标签: flutter dart bloc


    【解决方案1】:

    如果您的 WorkoutEvent Class 扩展了 equatable, 然后你需要添加这一行

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

    到你的UpdateWorkoutPageIndex 班级

    目的是通过props(属性)的[List]来判断两个[Equatables]是否相等。 因此,状态将被更新。

    【讨论】:

    • 我添加了它,但不幸的是这并没有解决问题。我相应地更新了问题中的代码。
    • 我在州级课程中缺少相同的内容。添加它,它的工作原理!
    • 这绝对是我更新值的诀窍。状态变化很大是不是很糟糕? Bloc 不应该防止状态更改和更新小部件吗?我在一个每秒更新的文本字段上有一个计时器。我希望让它更新文本而不一直重建状态。有什么建议吗?
    猜你喜欢
    • 2021-03-19
    • 2020-10-10
    • 2020-02-27
    • 2022-08-11
    • 2020-09-16
    • 2020-08-03
    • 2021-08-02
    • 2021-01-06
    • 2020-05-06
    相关资源
    最近更新 更多