【发布时间】:2021-05-17 01:41:36
【问题描述】:
我在这段代码的最后一行收到_CastError 错误
BlocBuilder buildUsernameField() {
return BlocBuilder<ProfileBloc, ProfileState>(
buildWhen: (previous, current) => previous != current && current is EditingUserInfo,
builder: (context, state) => TextField(
keyboardType: TextInputType.name,
controller: TextEditingController(
text: (state as EditingUserInfo).username.value),
这么说
I/flutter (26787): The following _CastError was thrown building BlocBuilder<ProfileBloc, ProfileState>(dirty, state:
I/flutter (26787): _BlocBuilderBaseState<ProfileBloc, ProfileState>#25b87):
I/flutter (26787): type 'Success' is not a subtype of type 'EditingUserInfo' in type cast
所以发生的事情是,当我处于另一个状态(成功)时,它会尝试构建该小部件。但是在buildWhen参数中,我指定了widget应该只在状态为EditingUserInfo时构建。
据我所知,这个错误不应该发生。
这是我的ProfileState:
part of 'profile_bloc.dart';
abstract class ProfileState extends Equatable {
const ProfileState();
@override
List<Object> get props => [];
}
class ProfileInitial extends ProfileState {}
class EditingUserInfo extends ProfileState {
final Username username;
final Bio bio;
final PhotoUrl photoUrl;
final City city;
final FormzStatus status;
const EditingUserInfo({
this.username = const Username.pure(),
this.bio = const Bio.pure(),
this.photoUrl = const PhotoUrl.pure(),
this.city = const City.pure(),
this.status = FormzStatus.pure,
});
EditingUserInfo copyWith({Username username, Bio bio, PhotoUrl photoUrl, City city, FormzStatus status}){
return EditingUserInfo(
username: username ?? this.username,
bio: bio ?? this.bio,
photoUrl: photoUrl ?? this.photoUrl,
city: city ?? this.city,
status: status ?? this.status,
);
}
@override
List<Object> get props => [username, bio, photoUrl, city];
}
class Loading extends ProfileState {}
class Error extends ProfileState {
final String message;
const Error({this.message});
@override
List<Object> get props => [message];
}
class Success extends ProfileState {
final String message;
const Success({this.message});
@override
List<Object> get props => [message];
}
【问题讨论】:
-
显示您的状态文件
ProfileState和扩展它的类。 -
我用我的 ProfileState 类更新了帖子