flutterdartbloc

Flutter bloc event is not getting called on initial screen load


I just started with flutter bloc and I want to call an event on screen initial load. I have the following code but the event AuthEventCheck is not getting called.

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => BlocProvider(
              create: (context) => AuthBloc()..add(AuthEventCheck()),
              child: const HomePage(),
            ),
      },
    );
  }
}

This is the bloc file

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';

part 'auth_event.dart';
part 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  AuthBloc() : super(AuthInitial()) {
    on<AuthEventCheck>((event, emit) {
      print('AuthEventCheck');
    });
  }
}


Why its not working and how can I call the event AuthEventCheck on screen initial load?


Solution

  • You can try not calling the add at the create of BlocBuilder,instead of this make HomePage StatefulWidget and write initState function and call it at initState so you create the state at the beginning of HomePage.And you must control state with BlocBuilder at homepage.

    Recommended Changes:

    make create like this => create: (context) => AuthBloc(),

    Make HomePage statefulWidget and write this initState

    void initState() {
          super.initState();
          context.read<AuthBloc>().add(AuthEventCheck());
    }
    
    body: BlocBuilder<AuthBloc, AuthState>(
        builder: (context, state) {
          if (state is AuthInitial) {
            return const Center(child: Text('Initial State'));
          }
          return const Center(child: Text('Other State'));
        },
      ),