首页 > 解决方案 > 如何从处于状态(flutter_bloc)的对象中获取值

问题描述

在构建器方法中,我达到了状态的值,例如

return BlocBuilder<UsersOwnProfileBloc, UsersOwnProfileState>(
   cubit: widget.bloc,
   builder: (context, state) {
      if (state is FetchedUserSettingState) {
      bool account = state.userSettings.publicAccount
}

但我需要从 initState 中获取值。我需要设置小部件的值。我尝试过这样的事情,但我得到了错误

 @override
  void initState() {
    super.initState();
     UsersOwnProfileState state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
     if (state is FetchedUserSettingState) {
       publicAccount = state.userSettings.publicAccount;
     }
} 

谁能告诉我如何在 initState 中获取状态值?

class UserSettingPage extends StatefulWidget {
  final UsersOwnProfileBloc bloc;

  const UserSettingPage({Key key, this.bloc}) : super(key: key);

  @override
  _UserSettingPageState createState() => _UserSettingPageState();
}

class _UserSettingPageState extends State<UserSettingPage> {
  bool newListingAlert;
  bool listingForSearchAlert;
  bool searchForListingAlert;
  bool followAlert;
  bool publicAccount;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
      if (state is FetchedUserSettingState) {
        publicAccount = state.userSettings.publicAccount;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<UsersOwnProfileBloc, UsersOwnProfileState>(
      cubit: widget.bloc,
      builder: (context, state) {
        if (state is FetchedUserSettingState) {
          return Scaffold(
            appBar: PreferredSize(
              preferredSize: Size.fromHeight(25.h),
              child: ListingEditAppBar(
                onCancel: () {
                  widget.bloc.add(FetchUserEvent(userId: CurrentUser.currentUser.id));
                  Navigator.pop(context);
                },
              ),
            ),
            body: Column(
              children: [
                PageTitle(title: "Preferences"),
                Expanded(
                  child: ListView(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text("Profilim herkese açık"),
                            Switch(
                              onChanged: (value) {
                                setState(() {
                                  publicAccount = value;
                                });
                              },
                              value: publicAccount,
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          );
        }
        return MyProgressIndicator();
      },
    );
  }
}

我已经添加了整个代码。我收到以下错误。

断言失败:布尔表达式不能为空相关的导致错误的小部件是 Switch

标签: flutterblocflutter-bloc

解决方案


如果你想访问 initState 中的状态,你需要使用它WidgetsBinding来访问它。但是,使用它可以确保构建您的小部件,然后触发获取值的方法。仅使用 BlocBuilder、Watch 或 Select 来获取您正在寻找的值会更快。

但是要回答您的问题,您可以执行以下操作

  WidgetsBinding.instance.addPostFrameCallback((_) {
    final state = BlocProvider.of<UsersOwnProfileBloc>(context).state;
    if (state is FetchedUserSettingState) {
      publicAccount = state.userSettings.publicAccount;
    }
  });

推荐阅读