Parama Artha
Parama Artha

Reputation: 77

How to fix bloc listener emit the same state twice?

Hi i have this problem where my app failed to navigate correctly to a new page after getting success state, here what it should be:

First Page -> Second Page (listen when success) -> Last Page

What it do instead: First Page -> Second Page (when success) -> Second Page -> Second Page -> Last Page -> Last Page -> Last Page

Here my code Bloc Listener on the Second Page:

//Bloc Provider on the first page
BlocProvider(
      create: (context) => GetIt.I<TransactionBloc>(),
      child: PayBillsKuisionerPageView(),
    )

//Bloc Listener on second Page
BlocConsumer<TransactionBloc, TransactionState>(
            listener: (context, state) {
              if (state.addTransactionStatus == AddTransactionStatus.success) {
                print('hehe');
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (_) => BlocProvider.value(
                              value: context.read<TransactionBloc>(),
                              child: PayBillsPinPage(),
                            )));
              }
            },
            builder: (context, state) {
              if (state.addTransactionStatus == AddTransactionStatus.loading) {
                return ElevatedButton(
                  label: Text('Lanjut'),
                  onPressed: () {},
                );
              }
              return ElevatedButton(
                onPressed: () {
                  context
                      .read<TransactionBloc>()
                      .add(AddTransaction(type: 'cash-deposit'));
                },
              );
            },
          ),

//Bloc Event
Future<void> _addTransaction(
    AddTransaction event,
    Emitter<TransactionState> emit,
  ) async {
    emit(
      state.copyWith(
        addTransactionStatus: AddTransactionStatus.loading,
        errorMessage: null,
      ),
    );
    try {
      
      final result = await repository.addTransaction(model: AddTransactionModel(
        accountNumber: state.accountNumber, type: event.type, transaction: TransactionDataModel(amount: state.amount)));
      
      emit(
        state.copyWith(
          addTransactionStatus: AddTransactionStatus.success,
          transactionId: result.transactionId
        ),
      );
    } catch (e) {
      emit(
        state.copyWith(addTransactionStatus: AddTransactionStatus.failed, errorMessage: '$e'),
      );
    }
  }

PS: it print 'hehe' twice in the console

any help would be appreciated

Upvotes: 0

Views: 51

Answers (0)

Related Questions