【发布时间】:2021-09-28 17:22:04
【问题描述】:
我正在尝试在 Flutter 中创建一个警报对话框,但是该对话框在 MaterialApp 下时不起作用,而是给出了错误。下面是代码:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Inputs and alerts'),
),
body: ElevatedButton(
child: const Text('Show Dialog'),
onPressed: () {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text('This is a text'),
content: Text('this is the content'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes'),
)
],
);
},
);
},
),
),
);
}
}
但是当我将 ElevatedButton 提取到一个独立的小部件时,警报对话框可以正常工作。代码如下:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Inputs and alerts'),
),
body: sn(),
),
);
}
}
class sn extends StatelessWidget {
const sn({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: ElevatedButton(
child: const Text('Show Dialog'),
onPressed: () {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: Text('This is a text'),
content: Text('this is the content'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: Text('Yes'),
)
],
);
},
);
},
),
);
}
}
谁能告诉我这种行为的原因?非常感谢任何帮助。
【问题讨论】:
-
好的!我得到了解决方案。但我不明白为什么会这样?如果您有任何想法,请解释一下吗?
-
我不认识,检查这个答案这将有助于stackoverflow.com/a/53296254/13418165
-
谢谢,兄弟。我之前没有经历过这个答案。它清除了很多。
标签: android flutter dart mobile