unice
unice

Reputation: 2842

How to trigger bloc listener with the same state multiple time?

My bloc returns NetworkErrorState if there is no internet connection. And it will show a widget with a 'Try Again' button. When I press the button when there is still no internet connection, it will return the same state and the same message and Failure. How will I trigger the bloc listener again with the same state?

Bloc State:

 class NetworkErrorState extends MyBlocState {
      final String message;
      final Failure failure;
    
      NetworkErrorState ({this.failure, this.message});
      @override
      List<Object> get props => [failure, message];
    }

Exception:

class ServerException implements Exception {
  final String message;

  ServerException({this.message});
}

Failure:

abstract class Failure extends Equatable {
  final List properties = const <dynamic>[];
  Failure([properties]);

  @override
  List<Object> get props => properties;
}

class ServerFailure extends Failure {
  final String message;

  ServerFailure({this.message});
  @override
  List<Object> get props => [message];
}

Upvotes: 3

Views: 3097

Answers (2)

Sai Phaneesh K.H.
Sai Phaneesh K.H.

Reputation: 11

class ServerFailure extends Failure {
  final String _id;
  final String message;

  ServerFailure({required this.message})
      : _id = DateTime.now().toIso8601String();
  @override
  List<Object> get props => [{message, _id}];
}

Hope this helps, had the same issue and after some brainstrorming came to this solution and it should work. I tried it this method with a simple form which validates for empty string input and the listerner was just triggering for the first time and for second attempt was not listening. After this method it triggers how many ever times you want. If need be you can use Uuid package to create unique IDs for every time rather than using DateTime.now().

Upvotes: 1

Robert Sandberg
Robert Sandberg

Reputation: 8635

I don't think it is possible, by design. But I see two very viable options. I would probably go with number 1...

  1. emit a different state between your two NetworkErrorStates. Pressing the "try again button" (the function that is called) could first emit e.g. RetryingConnectionState. Your ui could display something nice then?

Or...

  1. Another way to work around that is to pass an extra variable with the state that changes, so that it won't be recognized as the same state (make sure that variable is taken into consideration by equatable props). It could e.g. be reconnect attempt number or a timestamp when last retry was made.

Upvotes: 5

Related Questions