I just started to study the bloc and I have a question. I need to change the color when the state is selected, and according to my logic, I have to do state = Colors.red
, but unfortunately this is not the case. Can you please tell me what should I do to change the status?
Here is my bloc -
class SumBloc extends Bloc<Color, SumState> {
SumBloc() : super(SumNotChosen()) {
on<Color>((event, emit) {
final state = this.state;
if(state is SumSelected) {
emit(state.color) // ??????
}
});
}
}
Here are my states -
abstract class SumState {}
class SumNotChosen extends SumState{}
class SumSelected extends SumState{
final Color color;
SumSelected({required this.color});
}
When using bloc you should listen to events and change states accordingly.
sum_state.dart
part of 'sum_bloc.dart';
abstract class SumState {
final Color? color;
const SumState({this.color});
}
class SumInitial extends SumState {}
class SumSelected extends SumState {
const SumSelected({required super.color});
}
sum_event.dart
part of 'sum_bloc.dart';
abstract class SumEvent {}
class ColorSelected extends SumEvent {
final Color color;
ColorSelected({required this.color});
}
sum_bloc.dart
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
part 'sum_event.dart';
part 'sum_state.dart';
class SumBloc extends Bloc<SumEvent, SumState> {
SumBloc() : super(SumInitial()) {
on<ColorSelected>((event, emit) {
emit(SumSelected(color: event.color));
});
}
}
Here yous listen to SumSelected
event and emit new state