Я новичок в флаттер-муравье, пытающемся использовать блок/кубит
У меня есть состояние внутри файла cubit, и когда я пытаюсь передать состояние... состояние не меняется, и я не понимаю, почему
Это мой кубит файл:
//auth_cubit.dart
import 'package:flutter_bloc/flutter_bloc.dart';
part of 'auth_state.dart'; // here ide returns an error: The part-of directive must be the only directive in a part.
class AuthCubit extends Cubit<AuthState> { // The name 'AuthState' isn't a type so it can't be used as a type argument.
AuthCubit() : super(AuthState(
email: "Log in",
password: null,
firstName: "",
lastName: "",
genderId: 0,
ageGroupId: 0,
countryUuid: 0
));
void setCountryUuid(int countryUuid) => emit(AuthState(countryUuid: countryUuid));
}
//auth_state.dart
part of 'auth_cubit.dart';
class AuthState {
final email;
final password;
final firstName;
final lastName;
final genderId;
final ageGroupId;
final countryUuid;
const AuthState({
this.email, //string
this.password, //string
this.firstName, //string
this.lastName, //string
this.genderId, //int
this.ageGroupId, //int
this.countryUuid //int
});
}
Почему состояние не может соединиться с кубитом?
Сначала нужно исправить ошибку, см. выше часть части (ахах):
import 'package:flutter_bloc/flutter_bloc.dart';
part 'auth_state.dart'; // Just use part in the cubit
class AuthCubit extends Cubit<AuthState> { // This error should be gone
AuthCubit() : super(AuthState(
email: "Log in",
password: null,
firstName: "",
lastName: "",
genderId: 0,
ageGroupId: 0,
countryUuid: 0
));
void setCountryUuid(int countryUuid) => emit(AuthState(countryUuid: countryUuid));
}
После этого ваш локоть сможет излучать новое состояние.
Использование equable поможет обеспечить равенство значений.
По умолчанию == возвращает true, если два объекта являются одним и тем же экземпляром.
class AuthState extends Equatable {
final String? email;
final String? password;
final String? firstName;
final String? lastName;
final int? genderId;
final int? ageGroupId;
final int? countryUuid;
const AuthState({
this.email,
this.password,
this.firstName,
this.lastName,
this.genderId,
this.ageGroupId,
this.countryUuid,
});
AuthState copyWith({
String? email,
String? password,
String? firstName,
String? lastName,
int? genderId,
int? ageGroupId,
int? countryUuid,
}) {
return AuthState(
email: email ?? this.email,
password: password ?? this.password,
firstName: firstName ?? this.firstName,
lastName: lastName ?? this.lastName,
genderId: genderId ?? this.genderId,
ageGroupId: ageGroupId ?? this.ageGroupId,
countryUuid: countryUuid ?? this.countryUuid,
);
}
@override
List<Object?> get props =>
[email, password, firstName, lastName, genderId, ageGroupId, countryUuid];
}
выпустить новый экземпляр для обновления пользовательского интерфейса.
emit(state.copyWith(countryUuid: countryUuid));
Если вы используете
emit(AuthState(countryUuid: countryUuid))
, он всегда будет создавать новый экземпляр, другие файлы будут отсутствовать,