简体   繁体   English

如何从 state (flutter_bloc) 中的 object 中获取价值

[英]How to get value from an object which in the state (flutter_bloc)

in builder method I reach the value of state like在构建器方法中,我达到了 state 的值,例如

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

But I need to get the values from initState.但我需要从 initState 中获取值。 I need to set the values of the widget.我需要设置小部件的值。 I tried something like this but I got error我尝试过这样的事情,但我得到了错误

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

Can anyone show me how to get state value in initState?谁能告诉我如何在 initState 中获得 state 值?

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();
      },
    );
  }
}

I have added the whole code.我已经添加了整个代码。 I am getting the following error.我收到以下错误。

Failed assertion: boolean expression must not be null The relevant error-causing widget was Switch断言失败:boolean 表达式不能是 null 相关的导致错误的小部件是 Switch

If you would like to access the state within initState you will need to use WidgetsBinding to access this.如果您想在 initState 中访问 state,您将需要使用WidgetsBinding来访问它。 However, using this ensures that your widget is built and then triggers the method to get the value.但是,使用它可以确保构建您的小部件,然后触发获取值的方法。 It will be faster to just use the BlocBuilder, Watch, or Select to get the value you are looking for.仅使用 BlocBuilder、Watch 或 Select 来获得您正在寻找的价值会更快。

But to answer your question, you can do the following但是要回答您的问题,您可以执行以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM