I have the follwing code with a _checkCreds function. I want to show an alert when that button is pressed.
When I replace the print() statement with an AlertDialog(), I get a "No MaterialLocalizations found".
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
void _checkCreds(bool val) {
if(!val){
print("Warning, show alert here instead of print!");
return;
}
...
// Continue executing
}
Widget build(BuildContext context) {
return MaterialApp(
home: RaisedButton(
child: "Press me to trigger an alert!" ),
onPressed: () => _checkCreds(false),
);
}
}
-
api.flutter.dev/flutter/material/AlertDialog-class.htmlanmol.majhail– anmol.majhail2020年07月24日 14:50:26 +00:00Commented Jul 24, 2020 at 14:50
-
The docs don't include where the function should be calledusersina– usersina2020年07月24日 15:28:48 +00:00Commented Jul 24, 2020 at 15:28
-
Does this answer your question? How to make an AlertDialog in Flutter?Alok– Alok2020年07月24日 15:49:25 +00:00Commented Jul 24, 2020 at 15:49
-
1@Alok Too much for what I wanted, but I've figured it out thanks!usersina– usersina2020年07月24日 19:35:59 +00:00Commented Jul 24, 2020 at 19:35
2 Answers 2
I've figured it out, coming for a React environment I didn't know where "BuildContext" fits in all of this. After further investigation I passed the current context as an argument to the function that calls the Alert.
Above main():
Future<void> _ackAlert(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Error'),
content: const Text('Please enter a valid text'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
Inside the main widget:
Widget build(BuildContext context) {
return MaterialApp(
home: RaisedButton(
child: "Press me to trigger an alert!" ),
// I've added a parameter that takes the current context
onPressed: () => _checkCreds(false, context),
);
}
I think this is what you want:
void _checkCreds(bool val){//put it inside 'MyAppState' class
if(!val){
showDialog(
barrierDismissible: true,//tapping outside dialog will close the dialog if set 'true'
context: context,
builder: (context){
return Dialog(
//Add code here
);
}
);
}
...
// Continue executing
}
AlertDialog and Dialog has same properties except AlertDialog has content property whereas Dialog has child property. Both does same work.