Easy Dialogs using GetX
Intro
If you have read my post about snackBars using GetX, You already know how easy is it to work with GetX in Flutter.
Dialogs are an essential part of mobile Apps. They help to convey alerts and important messages as well as to do certain actions.
Normally in Flutter, shown below is a sample code for showing and Alert Dialog.
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Alert",
),
content: Text(
"This is sample Content",
),
),
);
That’s too many Lines of code for a Simple Dialog like this. But, thankfully GetX makes this easier. In GetX, we only have to use the following code,
Get.defaultDialog(
title: "Alert",
content: Text(
"This is a sample Content",
),
);
I think this makes a big difference.
Add Package
First of all, we have to add the get package into our pubspec.yaml file
dependencies:
flutter:
sdk: flutter
get: ^4.1.4 # Get the latest version from https://pub.dev/packages/get
Change to GetMaterialApp
To all navigation and routing things work with GetX, we have to change our MaterialApp to a GetMaterialApp. For this, we have to import the library first
import 'package:get/get.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp( // Changed from MaterialApp to GetMaterialApp
home: HomePage(),
);
}
}
If this step is not completed, it will throw an error
when we try to use something like Get.dialog()
.
We’re good to go now.
GetX default Dialog
This is the type of dialog which I have shown as an Example.
Get.defaultDialog(
title: "Alert!",
content: Text("This is a sample Content"),
)
Put the above code inside any onPressed or onTap method and see the magic.
GetX Dialog
This is also a simple way to show a dialog. But in this, we don’t have parameters like title and content, But we have to construct them manually. It accepts a widget and we have to build our Dialog from Scratch.
Get.dialog(
Text("This is a simple Dialog"),
)
the above code will show a simple dialog with the text, This is a simple Dialog. But it is not cool looking.
So we should always return a Dialog widget from Get.dialog and put anything we want to show the user as the child of the Dialog Widget.
End
You can find more articles related to GetX Here
Hope you found something useful here.
I’m always open to suggestions!
Let me know your suggestions and opinions in Twitter DM or drop a mail a [email protected].
If you’re feeling too generous, you can support me through Buy Me a Coffee.
Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.