在BlocBuilder中将类初始化为模型并得到错误

时间:2019-05-14 08:25:09

标签: dart flutter bloc

在我的应用程序中,我具有以下结构的模型,并且我想在BlocBuilder内初始化该模型,以更新ui元素,例如Text(),例如:

class _Login extends State<Login> {
  UserInfo _userInfo = UserInfo();

  LoginListingBloc loginListingBloc;

  @override
  void initState() {
    loginListingBloc = BlocProvider.of<LoginListingBloc>(context);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder(
        bloc: loginListingBloc,
        builder: (BuildContext context, LoginListingStates state) {
          if (state is LoginUninitializedState) {
          } else if (state is LoginFetchedState) {
            _userInfo = state.userInfo;

            print(_userInfo.name);
          }
          return Text("My Username from server is: $_userInfo.name");
        },
      ),
    );
  }
}

我不想创建诸如nameemailavatart之类的变量并将其填充在BlocBuilder内以使用它们,因为我拥有此类模型并且我认为我可以在BlocBuilder内部进行初始化,

不幸的是,我在运行应用程序时收到此错误:

  

以下ArgumentError被抛出   BlocBuilder(脏,   依赖项:[MediaQuery],状态:   _BlocBuilderBaseState#2342d):无效的参数

LoginListingStates类内容:

abstract class LoginListingStates {}

class LoginUninitializedState extends LoginListingStates {}

class LoginFetchingState extends LoginListingStates {}

class LoginFetchedState extends LoginListingStates {
  final UserInfo userInfo;

  LoginFetchedState({this.userInfo}) : assert(userInfo != null);
}

class LoginErrorState extends LoginListingStates {}

和我的UserInfo模型类:

class UserInfo {
  String _name;
  String _email;
  String _avatar;

  UserInfo();

  UserInfo.fromJson(Map<String, dynamic> json)
      : _name = json["name"],
        _email = json["email"],
        _avatar = json["avatar"],

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = _name;
    data['email'] = _email;
    data['avatar'] = _avatar;
    return data;
  }

  String get email => _email;

  String get name => _name;

  int get avatar=> _avatar;
}

0 个答案:

没有答案