首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >颤振BLoC‘BLoC’属性

颤振BLoC‘BLoC’属性
EN

Stack Overflow用户
提问于 2021-02-13 15:03:48
回答 1查看 5.9K关注 0票数 5

在这段代码的最后一行,我得到了一个_CastError错误

代码语言:javascript
复制
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),

我是说

代码语言:javascript
复制
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

代码语言:javascript
复制
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];
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-13 15:25:08

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

代码语言:javascript
复制
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)
}
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66186527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档