I'm trying to show a dialog popup whenever the user clicks on a button. However, whenever I test this the dialog will not show up and an exception will be thrown in Chrome console.
Exception message:
Uncaught TypeError: Cannot read properties of null (reading 'toString')
at Object.a9 (main.dart.js:16645)
at Object.DV (main.dart.js:4402)
at main.dart.js:65305
at b7F.a (main.dart.js:20524)
at b7F.$2 (main.dart.js:49122)
at Object.l (main.dart.js:20510)
at aUl.$0 (main.dart.js:65307)
at NQ.YO (main.dart.js:80893)
at Object.eval (eval at bio (main.dart.js:13895), <anonymous>:3:55)
at je.a5X (main.dart.js:76162)
and here's my dart code:
ElevatedButton(
onPressed: () async {
showDialog(context: context, builder: (_){
return const AlertDialog(title: Text("Test"),);
});
},
child: const Text("Test")
)
I have tried to put await
before showDialog
but still see the same issue
CodePudding user response:
There are two ways to declare Alert
1.By create separate method/function
showMyDialog() async {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: const <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to approve of this message?'),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Approve'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Your Widget:
ElevatedButton(
onPressed: () async {
showMyDialog();
},
child: const Text(
"Pressed Me",
),
),
By declare
OnPressed
functionElevatedButton( onPressed: () => showDialog<String>( context: context, builder: (BuildContext context) => AlertDialog( title: const Text( 'AlertDialog Title', ), content: const Text( 'AlertDialog description', ), actions: <Widget>[ TextButton( onPressed: () => Navigator.pop( context, 'Cancel', ), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.pop( context, 'OK', ), child: const Text( 'OK', ), ), ], ), ), child: const Text( 'Pressed Me', ), ),
Refer Documentation here
You Can refer my answers here and here also for AlertDialog
If you dismiss your alert automatically refer my answer here
Test Both solution here
CodePudding user response:
So I found out what was the issue, on my main MaterialApp definition, I used the builder
instead of home
or route
. And that caused the issue. However, when I switched to using home
instead, it worked like a charm. Thank you