Home > Software design >  How to call bloc inside initState method?
How to call bloc inside initState method?

Time:07-13

I need to call the fetchProfile() method and get the profileState.user data in the initState method right after the page opens. Tell me, how can I write this correctly, how can I correctly call Cubit inside the initState method?

 @override
  void initState() {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _emailDialog();
    });
    super.initState();
  }

cubit

class ProfileCubit extends Cubit<ProfileState> {
  final UserRepository _repository;
  ProfileCubit(this._repository) : super(ProfileInitial());

  Future fetchProfile() async {
    try {
      final User? user = await _repository.me();
      if(user != null) {
        emit(ProfileLoaded(user));
      } else {
        emit(ProfileError());
      }
    } catch (_) {
      emit(ProfileError());
    }
  }

state

abstract class ProfileState {}

class ProfileInitial extends ProfileState {}

class ProfileLoaded extends ProfileState {
  final User? user;
  ProfileLoaded(this.user);
}

class ProfileError extends ProfileState {}

CodePudding user response:

You can check the Readme of flutter_bloc. There is a full tutorial and you can learn a lot.

@override
void initState() {
  super.initState();
  context.read<ProfileCubit>().fetchProfile()
}
 

CodePudding user response:

If your intention is to run the method fetchProfile directly when the widget (page in this case) will be built, I'd run the method when providing the bloc using cascade notation as such:

home: BlocProvider(
        create: (_) => ProfileCubit()..fetchProfile(),
        child: YourPageOrWidget(),
      ),

The fetchProfile() method will be called as soon as the Bloc/Cubit is created.

Note that by default, the cubit is created lazily, so it will be created when needed by a BlocBuilder or similar. You can toggle that so it isn't created lazily.

  • Related