我正在基于flutter alertDialog构建一个通用的flutter小部件,我希望将它作为一个单独的小部件,可以在其他小部件中使用onPressed方法调用。
目前,alertDialog 使用 onPressed 方法打开,该方法是 ElevatedButton 小部件中当前小部件的一部分。我想摆脱这个 ElevatedButton,因为打开 alertDialog 的按钮是其他小部件的一部分。
Class AppAlertDialog extends StatelessWidget {
const AppAlertDialog({
required this.buttonName,
required this.title,
required this.content,
required this.secondaryButtonName,
required this.primaryButtonName,
Key? key,
}) : super(key: key);
final String buttonName;
final String title;
final String content;
final String secondaryButtonName;
final String primaryButtonName;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => _showAlertDialog(context),
child: Text(buttonName),
);
//Get rid of this ElevatedButton and call the _showAlertDialog method to open the
//alertDialog from other onPressed methods in other files
}
_showAlertDialog(BuildContext context) {
final titleTextStyle = Theme.of(context).textTheme.headline5!;
const buttonPadding = EdgeInsets.all(20);
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text(
title,
style: titleTextStyle,
),
content: Text(content),
contentPadding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
actions: <Widget>[
ElevatedButton(
onPressed: () => Navigator.pop(context),
style: ElevatedButton.styleFrom(
padding: buttonPadding,
primary: SharedColorsButton.secondaryButtonBgColor,
onPrimary: SharedColorsButton.secondaryButtonFgColor,
side: const BorderSide(
color: SharedColorsInputDecoration.borderColor,
),
),
child: Text(secondaryButtonName),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
padding: buttonPadding,
),
onPressed: () => Navigator.pop(context),
child: Text(primaryButtonName),
),
],
actionsPadding: const EdgeInsets.fromLTRB(24, 16, 24, 16),
),
);
}
}