Home > Enterprise >  How to replace copyWith so as not to copy, but to create a new state?
How to replace copyWith so as not to copy, but to create a new state?

Time:05-18

I have a bloc which is responsible for switching indexes in the Navogation Bottom Bar.It is implemented in such a way that it copies the old state and changes it. I need to replace copyWith and make it not copy but create a new state. How can this be implemented and rewritten given bloc?

class BottomNavyBloc extends Bloc<BottomNavyEvent, BottomNavyState> {
  BottomNavyBloc() : super(const BottomNavyState()) {
    on<ChangePageEvent>(
          (event, emit) => emit(
        state.copyWith(index: event.index),
      ),
    );
  }
}

abstract class BottomNavyEvent extends Equatable {
  const BottomNavyEvent();

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

class ChangePageEvent extends BottomNavyEvent {
  final int index;

  const ChangePageEvent({
    required this.index,
  });

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

My state:

class BottomNavyState extends Equatable {
  const BottomNavyState({
    this.index = 0,
  });

  final int index;

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

class ChangePageState extends BottomNavyState {

}

CodePudding user response:

We use

emit(state.copyWith(index: event.index))

to say that we are copying all the elements from the previous state by changing index.

Your state BottomNavyState has only one variable as of now. So, the above copyWith acts similar to using emitting new state.

We should not try to change or override the method copyWith because it beats the method's actual purpose.

Instead, you could use

emit(BottomNavyState(index: event.index))

to use a new state constructor instead of copying from previous state.

  • Related