0

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?

Anil
  • 9
  • 2

2 Answers2

0

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!"));
  }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • It is just not right. – Thioby Feb 02 '23 at 10:40
  • @Thioby can you explain what's not right with the approach given in the answer? from what I see it supports your position as well: emitting state containing data. The only question I have to tis answer is why does this method have a return type? – Olga Feb 02 '23 at 10:56
0

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

Thioby
  • 86
  • 1
  • 1
  • What you are saying is ideal situation, and everybody loves clear state management, but don't be so strict :) sometimes breaking patterns (including this one) is almost inevitable – Olga Feb 02 '23 at 11:00