Flutter BLoC `buildWhen`属性

9wbgstp7  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(124)

我在这段代码的最后一行得到一个_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参数中,我指定了小部件只应该在状态为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];
}

eqoofvh9

eqoofvh91#

您仍然需要检查状态变量是否是正确的状态。每次更改状态时都会检查状态,因此状态变量仍然可以是不同的状态,除非buildWhen条件为真,否则它不会重新构建。

BlocBuilder buildUsernameField() {
return BlocBuilder<ProfileBloc, ProfileState>(
buildWhen: (previous, current) => previous != current && current is EditingUserInfo,
builder: (context, state) {
 if(state is EditingUserInfo) {
  return TextField(
  keyboardType: TextInputType.name,
  controller: TextEditingController(
      text: state.username.info)
}
}

字符串

dnph8jn4

dnph8jn42#

以下是对你的提问user54517的明确回答:
buildWhen会在区块状态改变时阻止你的小部件重新构建,但如果框架出于任何其他原因重新构建它(例如,如果它的父组件之一需要重新构建...),它不会阻止它。
这就是为什么您仍然需要在构建器方法中检查状态的原因。
来源:https://github.com/felangel/bloc/issues/1413#issuecomment-655568783

相关问题