Flutter: how to wait for entire async method to finish before the next line runs

Issue

I’m running the script below:

TextButton(
  onPressed: () async {
    try {
      await BlocProvider.of<RoomCubit>(context).createRoom(test);
      await BlocProvider.of<PlayersCubit>(context) <---- Point 1
      .addPlayer(test.roomId, testPlayer);
      BlocProvider.of<NavigatorCubit>(context) <---- Point 2
                        .moveToLobby(context);
    } catch (e) {}
  },
  child: Text("Create room"),
)

class PlayersCubit extends Cubit<PlayerState> {
  PlayersCubit() : super(PlayerInitial());
    
  final PlayerRepository _playerRepository = PlayerRepository();
  Future<void> addPlayer(String roomId, Player player) async {
    emit(PlayerLoading());
    try {
      await _playerRepository.addPlayer(roomId, player);
      List<Player> playerList = await _playerRepository.playerList(roomId);
      emit(PlayerLoaded(player, playerList));
     } 
     catch (e) {}
  }
}
class NavigatorCubit extends Cubit<NavigatorState> {
  NavigatorCubit() : super(NavigatorInitial());
  late RoomState _roomState;
  late PlayerState _playerState;

  void moveToLobby(BuildContext context) {
    print("$_roomState, $_playerState");
    switch (_roomState is RoomLoaded && _playerState is PlayerLoaded) {
      case true:
        {
          Navigator.popAndPushNamed(
            context,
            "/Room",
          );
        }
        break;
      case false:
        {
          Navigator.pop(context);
        }
        break;
      default:
    }
  }

  void getRoomState(RoomState roomState) {
    _roomState = roomState;
  }

  void getPlayerState(PlayerState playerState) {
    _playerState = playerState;
  }
}

What I want it to do is emit PlayerLoaded from the PlayersCubit at the point 1, and then use that state in the NavigatorCubit at Point 2. However, even though I’ve put await at point 1 – the method at point 2 starts running before a state is emitted at point 1.

Is there a way I can make the next part wait before the state is emitted at point 1 without setting a timer?

Solution

What worked for me was quite simple, passed in the playerState and roomState as parameters to moveToLobby function in the NavigatorCubit.

It seems like the async functions only actually wait for any steps that include the await, otherwise all other lines of code are run synchronously.

Answered By – ImaGiraffe

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.