skip to Main Content

Is it ok to return a value from a Cubit state function or is it better to emit a state and use BlocListener?

Future<Game?> addGame(List<String> players, int numOfRounds) async {
  try {
    Game game = await repository.addGame(DateTime.now(), players, numOfRounds);
    return game;
  } on Exception {
    emit(GamesError(message: "Could not fetch the list, please try again later!"));
  }
}

The widget that calls this function adds a game and then redirects to a new page and passes the game object to it.

This works but it doesn’t feel like it is the right approach. Is it ok to do this or should I be emitting a new state and using the BlocListener to redirect to the new page?

2

Answers


  1. It is ok, but not preferred.

    Presently the function addGame returns a future, so you would have to use FutureBuilder to display it’s value.

    Instead emit state having containing the value,Now you can use BlocListener and BlocBuilder to display the value of game produced in the function addGame. So now the purpose of using bloc makes sense.

    Use code like:

    Future<Game?> addGame(List<String> players, int numOfRounds) async {
      try {
        Game game = await repository.addGame(DateTime.now(), players, numOfRounds);
        emit(GameLoaded(game: game); // 👈 Use it this way
      } on Exception {
        emit(GamesError(message: "Could not fetch the list, please try again later!"));
      }
    }
    
    Login or Signup to reply.
  2. Of course, it’s not.

    Bloc/Cubit is the single source of truth for the widget. All data that comes to the widget should be passed via state, one source. If you return values from Cubit methods, you are breaking the whole concept of the Bloc pattern.

    Bloc data flow

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search