Bloc Consumer is not listening to states

136

This ColorsCubit cubit = ColorsCubit(); is different from the cubit instance you're listening to.

You could do this:

  • ColorsCubit? cubit;

  • Then inside the BlocConsumer method assign your cubit

  • And finally, call the methods you want.

Your code would look like this now:

class _HomeScreenState extends State<HomeScreen> {
  ColorsCubit? cubit;
 
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => ColorsCubit(),
        child: BlocConsumer<ColorsCubit, ColorsStates>(
          listener: (context,ColorsStates state) {
            if (state is InitialState) print("in initial state");
            if(state is AddState)print('add state');
          },
          builder: (context,ColorsStates state) {

cubit??= context.read<ColorsCubit>(); // assign cubit if it's not already assigned

            return Scaffold(
              body: Center(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    TextButton(onPressed: ()=>cubit.add(), child: Text("add")),
                    Text(cubit.count.toString()),
                    TextButton(onPressed: ()=>cubit.minus(), child: Text("minus")),
                  ],
                ),
              ),
            );
          },
        ));
  }
}

You could also consider this approach: Instead of using BlocProvider, use BlocProvider.value, and put your cubit as the value. This way you don't need to do what I did in the above code

Share:
136
mohamed alaa
Author by

mohamed alaa

Updated on January 03, 2023

Comments

  • mohamed alaa
    mohamed alaa over 1 year

    when i press the add or minus button the number doesn't change and the bloc consumer doesn't listen to states i don't know the reason i tried every thing but nothing worked with me i want to know how to listen to changes and make the number change when i press the buttons add or minus

    `

    class HomeScreen extends StatefulWidget {
      const HomeScreen({Key? key}) : super(key: key);
    
      @override
      State<HomeScreen> createState() => _HomeScreenState();
    }
    
    class _HomeScreenState extends State<HomeScreen> {
      ColorsCubit cubit = ColorsCubit();
     
      @override
      Widget build(BuildContext context) {
        return BlocProvider(
            create: (context) => ColorsCubit(),
            child: BlocConsumer<ColorsCubit, ColorsStates>(
              listener: (context,ColorsStates state) {
                if (state is InitialState) print("in initial state");
                if(state is AddState)print('add state');
              },
              builder: (context,ColorsStates state) {
                return Scaffold(
                  body: Center(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        TextButton(onPressed: ()=>cubit.add(), child: Text("add")),
                        Text(cubit.count.toString()),
                        TextButton(onPressed: ()=>cubit.minus(), child: Text("minus")),
                      ],
                    ),
                  ),
                );
              },
            ));
      }
    }
    
    // this is cubit class
    
    
    class ColorsCubit extends Cubit<ColorsStates>{
      ColorsCubit() : super(InitialState());
    
      static ColorsCubit get(context)=>BlocProvider.of(context);
    
      int count=0;
    
      void add(){
        count++;
        emit(AddState());
      }
    
      void minus(){
        count++;
        emit(MinusState());
     }
    
    }
    
    // this is states class
    
    
    abstract class ColorsStates{}
    
    class InitialState extends ColorsStates{}
    
    class AddState extends ColorsStates{}
    
    class MinusState extends ColorsStates{}
    

    `

  • mohamed alaa
    mohamed alaa about 2 years
    but if i need to call a method from the ColorBloc in the initState how can i call it
  • Aron
    Aron about 2 years
    Create the BlocProvider outside of that widget (e.g, when you return the widget just wrap it with BlocProvider), then in initState of your widget you can do context.read<YourCubit>().yourMethod();
  • Nico Spencer
    Nico Spencer about 2 years
    I would create the instance as a member of the state, as you did in your question, and then use the BlocProvider.value constructor. This will use the existing instance of creating a new instance.
  • mohamed alaa
    mohamed alaa about 2 years
    but the initState is called before building the widget
  • Aron
    Aron about 2 years
    @mohamedalaa did you try the solution I posted?
  • mohamed alaa
    mohamed alaa about 2 years
    yes thank you i tried your solution and it worked for me but i found another problem and solved it by assigning the Bloc Provider above the material thank you so much
  • Aron
    Aron about 2 years
    Glad it helped. please consider marking the answer