Forum

Flutter Alert widge...
 
Notifications
Clear all

Flutter Alert widgets in separate files.


Igor Karelin
(@ikarelin)
Member Admin
Joined: 2 years ago
Posts: 19
Topic starter  

Hello all !

I want to put all of my alert dialogs and modal windows in a separate file and to be able to access them from different parts of code in my app.

Something like this:

showAlertDialog(String _title, String _message)

Do I need to pass the context to modal window ?

And how can I receive an output from modal controller to the parent widget ?


Quote
Igor Karelin
(@ikarelin)
Member Admin
Joined: 2 years ago
Posts: 19
Topic starter  

showDialog is already a top level function you can call.

https://api.flutter.dev/flutter/material/showDialog.html

It requires a BuildContext and a WidgetBuilder, which is a function that receives a context as argument and must return a Widget. This widget will most of the time be an instance of Dialog (AlertDialog inherits Dialog).

So in your case what I would do is create a separate file with methods which return WidgetBuilders for each dialog on your app.

ex:

WidgetBuilder myDialogBuilder({String title, String message, dynamic returnValue}) {
 
return (BuildContext context) => AlertDialog(
    title
: Text(title),
    content
: SingleChildScrollView(child: Text(message)),
    actions
: [
     
FlatButton(
        onPress
: () => Navigator.of(context).pop(returnValue),
        child
: Text('OK'),
     
),
   
]
 
);
}

Then inside any widget you can call

final returnedValue = await showDialog(
  context
: context,
  builder
: myDialogBuilder(title: 'Sample Title', message: 'Sample message', returnValue: true),
);

if (returnedValue == true) {
 
print('User pressed OK on my dialog');
}

Dismissing the dialog by touching outside it will pop the dialog passing "null", that's why I wrote "if (returnedValue == true)". If that's the case it means the user pressed OK, otherwise he dismissed the dialog by touching outside of it.

Of course you can have multiple methods on your external file and each one can have any number of actions. You can extend the technique above so that each method receives return values for each action as arguments or you can even make the "actions" list an argument of your function.


ReplyQuote
Share: