我有下面带有_checkCreds函数的代码。我想在按下该按钮时显示警报。
当我用AlertDialog()替换print()语句时,出现“找不到MaterialLocalizations”。
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),
);
}
}
答案 0 :(得分:1)
我已经弄清楚了,来到一个React环境,我不知道“ BuildContext”在所有这些环境中都适合。经过进一步调查,我将当前上下文作为参数传递给了调用Alert的函数。
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();
},
),
],
);
},
);
}
在主窗口小部件内:
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),
);
}
答案 1 :(得分:0)
我想这就是你想要的:
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
和Dialog
具有相同的属性,除了AlertDialog具有content
属性而Dialog具有child
属性。两者的工作相同。