skip to Main Content

I want an event to be sent to the bloc when the page loads. The problem is that the event is not sent to the bloc. What could be the problem?
I’ve done this many times with no problems. I can’t understand what’s wrong now.

class Page extends StatelessWidget {
  static PageRoute route() {
    return FadePageRoute(page: Page());
  }

  const Page({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<Bloc>(
        create: (context) => NewsBloc(GetIt.instance<Service>())
          ..add(Event(189)),
        child: _PageFlow());
  }
}

2

Answers


  1. When use bloc, you must seperate between create bloc and send event bloc.

    Below code is for create bloc.

    @override
    Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => NewsBloc(),
        child: _PageFlow());
    }
    

    If you want to send event to bloc, do inside the _PageFlow(). Example below i replace _PageFlow() with GestureDetector

    @override
    Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => NewsBloc(),
        child: GestureDetector(
                 onTap: () {
                   BlocProvider.of<NewsBloc>(context).add(Event(189));
                 }
               ),
    }
    
    Login or Signup to reply.
    1. First, you need to check in your bloc, the event that you will add has registered or not, you can check in your Bloc, example:
    class NewsBloc extends Bloc<NewsEvent, NewsState> {
      NewsBloc() : super(const NewsState()) {
        on<Event>(_onEvent);
        // Other events are registered below, maybe
      }
    
    1. Check to see if your UI has a widget that listens to Bloc’s state changes. Check to see if you use BlocBuilder or BlocListener or BlocConsumer or context.watch or context.select to make changes or build interfaces based on state or not.

    2. Because a Bloc is created lazily by default, when has event added and state listener, bloc will created. If you want to create a Bloc immediately, you can set lazy in BlocProvider to true.

    Hope my explanation will help in your problem. Happy coding 🙌

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search