I have a BloC
through which I receive data. But I ran into the problem that there are no different states so that I can display the loading indicator and handle errors if there are any. Can you tell me how can I modify this BloC
class to have different states MyCarsLoading, MyCarLoaded so that I can display the loading indicator in the appropriate state?
bloc
class MycarsCubit extends Cubit<MycarsState> {
MycarsCubit()
: super(MycarsInitial(
number: '',
type: '',
));
String number = '';
String type = '';
void clear() {
number = '';
type = '';
}
void change({
required String numberText,
required String typeText,
}) {
number = numberText;
type = typeText;
emit(MycarsInitial(
number: number,
type: type,
));
}
}
state
abstract class MycarsState {}
class MycarsInitial extends MycarsState {
String number;
String type;
MycarsInitial({
required this.number,
required this.type,
});
}
CodePudding user response:
I usually do this using the freezed
package with cubit, but without that you could do something like this:
class MycarsState extends Equatable {
final String number;
final String type;
const MycarsState._({
this.number = '',
this.type = '',
});
const MycarsState.initial() : this._();
const MycarsState.loading() : this._();
const MycarsState.loaded({required String number, required String type})
: this._(number: number, type: type);
@override
List<Object> get props => [number, type];
}
Then you can do like this:
void change({
required String numberText,
required String typeText,
}) {
emit(const MycarsState.loading());
number = numberText;
type = typeText;
emit(MycarsState.loaded(
number: number,
type: type,
));
}
CodePudding user response:
https://bloclibrary.dev/#/flutterweathertutorial?id=weather-state You can see here how it is handled.