Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ShowDialog using children is deprecated how to use it the other way?

Tags:

flutter

dart

I am trying to use showDialog in the following manner

showDialog(context: context,child:new Text("Hello Dialgo"));

The above works fine however it states that child parameter has been deprecated and the alternative way is to :

'Instead of using the "child" argument, return the child from a closure ' 'provided to the "builder" argument. This will ensure that the BuildContext ' 'is appropriate for widgets built in the dialog.'

I am not sure what that means. Any simple example here would be appreciated.

like image 445
MistyD Avatar asked May 02 '18 22:05

MistyD


3 Answers

Change it it

showDialog(
   context: context,
   builder: (_) => new Text("Hello Dialgo")
);

If you need the context from within the dialog change builder: (_) => to builder: (BuildContext context) =>

Because the Builder is a function handler, we need to create a function which accepts a single argument (BuildContext) and returns a Widget.

Syntax can either be:

(BuildContext context) => new Text('...');

or

(BuildContext context) {
    return new Text('...')
}

They are equivalent, though the second one can have more than one line

See an example here: https://github.com/aqwert/flutter_auth_starter/blob/master/lib/core/dialogs/showError_dialog.dart

like image 138
aqwert Avatar answered Nov 07 '22 20:11

aqwert


The child deprecated. If you look the this property, you can this warning.

Instead of using the "child" argument, return the child from a closure provided to the "builder" argument. This will ensure that the BuildContext is appropriate for widgets built in the dialog.

If you want to use builder, only write a function that returns your widget.

Example usage in my loader function

void showLoader(BuildContext context) {
  showDialog(context: context, builder: (BuildContext context) => new ProgressHUD(
    color: Colors.white,
    containerColor: Theme.of(context).primaryColor,
  ));
}

Usage

// Start to show loader
showLoader(context);
// Do a async job and wait it
await do();
// Hide the loader
Navigator.pop(context);
like image 1
Anilcan Avatar answered Nov 07 '22 22:11

Anilcan


We can assign text widget to the alert variable, like this:

var alert = new Text("Hello dialog");

Since the child is deprecated:

showDialog(context: context, child: alert);

we can write it like this:

showDialog(context: context, builder: (_) => alert);

If you want to create more complex dialog, you can redefine alert like this:

var alert = new AlertDialog(
    title: new Text('App'),
    content: new Text(message),
    actions: <Widget>[
      new FlatButton(onPressed: () {Navigator.pop(context);},
          child: new Text('OK'))
    ],
  );

and use it the same as above.

like image 1
miloss Avatar answered Nov 07 '22 22:11

miloss