Flutter. Show dialogs, toasts, etc. in your ViewModel/Controller without BuildContext

Yuri Novicow
Easy Flutter
Published in
3 min readNov 11, 2024

--

One of the best ideas of GetX is showing dialogs, toasts, snackbars, and sheets without BuildContext.

It is extremely convenient since we can show a dialog or a toast from the Controller instead of View.

If you are a member, please continue, otherwise, read the full story here.

Consider an example from a recent article.
We have a checkers game and we check the win condition after every move:

game_controller.dart

void movePiece() {
...
checkForVictory();
}

void checkForVictory() {
...
if (isVictory){
DialogManager().showWinDialog();
} else {
DialogManager().showDefeatDialog();
}
}

dialog_manager.dart

void showWinDialog(){
Get.dialog(
//no context required
)
}

The dialog is not shown without context, actually. It would be impossible I guess. But, GetX holds the BuildContext object of the last screen in the navigator stack and uses this context internally to show dialogs (toasts and so on).

This context is always available via Get.context property and can be used, for example, with third-party dialog packages.

--

--

Yuri Novicow
Yuri Novicow

Written by Yuri Novicow

20 years in software development. Writes about Flutter. Always looks for the most efficient paths. Shares secrets openly.

Responses (4)