How to get the latest updated State with Bloc?

Viewed 27

I have a problem concerning the latest updated bloc state. I have a button with onPressed function:

  1. First i trigger an Event, which changes the state
  2. Immediately after i retrieve the state, but its value is not updated to the latest event. To retrieve the state i use state from the BlocBuilder or the state from the context BlocProvider.of(context).state, but nothing works!!!

Do you have any ideas on how to retrieve the latest state version? Thanks. The code below:

class InputWidget extends StatefulWidget {
  const InputWidget({Key? key}) : super(key: key);

  @override
  State<InputWidget> createState() => _InputWidgetState();
}

class _InputWidgetState extends State<InputWidget> {
  late TextEditingController amountController;
  String? categoryValue;
  String? typeValue;

  @override
  void initState() {
    super.initState();
    amountController = TextEditingController();
  }

  @override
  void dispose() {
    amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<QuizBloc, QuizState>(
      builder: (context, state) {
        return Form(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () {
                  BlocProvider.of<QuizBloc>(context).add(
                    const QuizEvent.getQuizPressed(),
                  );
                  // Here i retrieve the state, the aim is to navigate to another page if 
                   //state is...
                  if (BlocProvider.of<QuizBloc>(context).state.value || state.value) {
                  context.router.push(const QuizRoute());}
                },
                child: const Text(
                  'Start the quiz',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

2 Answers

You are not showing the bloc code. But my guess is, you are sending the same state with updated values. This does not work (there is a way, but that is not the typical logic). You need to send another state first.

So let‘s assume you have the state ˋexpectInputˋ and then you send the event ˋselectedˋ - inside the bloc the logic for this event would first yield the event ˋinProgressˋ, then comes the logic and finally you yield ˋexpectInputˋ again

I solved the problem by using a BLocListener() that allows me to navigate to new page when the state value is true. It seems to be working because it gives me the latest state.

Related