0

I'm facing a problem in BlocLibrary(https://bloclibrary.dev/) I need to receive same state in BlocListner/BlocBuilder, let me explain in code: This is Bloc(for little explain):

class CounterBloc extends Bloc<CounterEvent, AppState> {
  @override
  AppState get initialState => InititalState();

  @override
  Stream<AppState> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.getState:
        yield Counter(value: 0); 
        break;
  }

HERE IS STATE CLASS:

import 'package:flutter_bloc/flutter_bloc.dart';
enum StateEvent { getState }

abstract class AppState extends Equatable {
  const AppState();

  @override
  List<Object> get props => [];
}


class Counter extends AppState {
  final int count;
  const Counter({@required this.count});
  @override
  List<Object> get props => [count];

  @override
  String toString() => 'Counter { count: $count }';
}

Here you go for my bloc listener/builder:

BlocListener<CounterBloc, AppState>(
    listener: (context, state) {
      if (state is Counter) {

  **Here I needed same state, means if I press getState, it should print 0 everytime**
        print(state. value);

      }
    },
    child: BlocBuilder<CounterBloc, AppState>(
      builder: (context, state) {
        return Center(
          child: Text(
            '${value}',
            style: TextStyle(fontSize: 24.0),
          ),
        );
      },
    ),
  )
Mateen
  • 418
  • 1
  • 3
  • 12
  • BlocListener should have a **bloc** parameter defined that points to the bloc class you want to listen to. – Thepeanut Mar 28 '20 at 12:32
  • If I pres once, I can get result means can print. But if I press again and again, it won't receive – Mateen Mar 28 '20 at 12:33
  • Then your **Counter** state definition is missing **props** function call. Show your **Counter** class. – Thepeanut Mar 28 '20 at 12:35
  • @Thepeanut I've updated question with State Class – Mateen Mar 28 '20 at 12:37
  • 1
    Ok, I missed the part where you said that you don't change the **count** variable. Bloc is made so that it doesn't push a new state if it's the same as the old one. This is why listener is firing once only, because the **count** didn't change. – Thepeanut Mar 28 '20 at 12:42

1 Answers1

3

Change your AppState, you can read more about Equatable usage here. This post is mostly a duplication of this.

You should not use Equatable if you want the same state back-to-back to trigger multiple transitions.

abstract class AppState { 
  const AppState();
} 

class Counter extends AppState { 
  final int count; 

  const Counter({@required this.count}); 

  @override
  String toString() => 'Increment { count: $count }'; 
} 
Federick Jonathan
  • 2,726
  • 2
  • 13
  • 26