Im currently having issues with my first bloc made from 0, it supposed to throw an error once a number reaches a certain number, but i noticed through testing that the event is not receiving any data at all, i have no idea what im doing wrong.
I can confirm that the event is being triggered, on changed the textfield fires the event.
I dont know if it matters yet but if try to int.parse it i recieve null.
Widget with the string that should be sent to the event.
class Daytextfield extends StatelessWidget {
Daytextfield({
Key? key,
required this.digits,
required this.hint,
}) : super(key: key);
final int digits;
final String hint;
final String texto = '';
@override
Widget build(BuildContext context) {
final TextEditingController dias = TextEditingController(text: texto);
Color color = Colors.black;
return BlocConsumer<DaysBloc, DaysState>(
listener: (context, state) {
if(state is DaysIncorrectState){
color = Colors.red;
} else if (state is DaysCorrectState){
color = Colors.green;
}
},
builder: (context, state) {
return TextFormField(
onChanged: (value) {
BlocProvider.of<DaysBloc>(context).add(DaysChangedEvent(texto: texto));
print(state);
// var ree = int.tryParse(texto);
print(texto);
},
controller: dias,
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
textAlign: TextAlign.center,
cursorColor: Color.fromARGB(148, 66, 63, 63),
style: Theme.of(context)
.textTheme
.headline1!
.copyWith(fontSize: 20, color: color),
Blocs
class DaysBloc extends Bloc<DaysEvent, DaysState> {
int max = 360;
DaysBloc() : super(DaysInitial()) {
on<DaysChangedEvent>((event, emit) {
if(event.texto == '123') {emit(DaysIncorrectState(texto: event.texto));}
else emit(DaysCorrectState(texto: event.texto));
});
}
}
abstract class DaysEvent extends Equatable {
const DaysEvent();
@override
List<Object> get props => [];
}
class DaysChangedEvent extends DaysEvent {
String texto;
DaysChangedEvent({
required this.texto,
});
@override
List<Object> get props => [texto];
}
class DaysInitial extends DaysState {}
class DaysCorrectState extends DaysState {
String texto;
DaysCorrectState({
required this.texto,
});
@override
List<Object> get props => [texto];
}
class DaysIncorrectState extends DaysState {
String texto;
DaysIncorrectState({
required this.texto,
});
@override
List<Object> get props => [texto];
}
2
Answers
Replace
BlocProvider.of<DaysBloc>(context).add(DaysChangedEvent(texto: texto));
with
BlocProvider.of<DaysBloc>(context).add(DaysChangedEvent(texto: value));
texto
is a final empty string hence you might be receiving empty string as event every time.In this line
replace
(texto:texto)
with(texto:value)
So It will look like this
That should do the work.