Ali Özen
Ali Özen

Reputation: 83

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

in builder method I reach the value of state like

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. 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?

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

Upvotes: 3

Views: 9156

Answers (1)

mrgnhnt96
mrgnhnt96

Reputation: 3945

If you would like to access the state within initState you will need to use WidgetsBinding to access this. 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.

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

Upvotes: 6

Related Questions