[英]Is it possible to pass class as a parameter in a function in Flutter?
在這里,我有一個實用程序 class,其中我有一個 function 用於顯示 DialogBox,所以我正在嘗試制作一個 AlertDialog Box,它可以在整個項目的任何地方使用。
因此,我必須將標題、描述作為參數傳遞,並且還想傳遞 Class 名稱,以便在按下警報對話框內的按鈕時,我們可以導航到該屏幕
class DialogBox {
static DialogBox dialogBox = null;
static DialogBox getInstance() {
if (dialogBox == null) {
dialogBox = DialogBox();
}
return dialogBox;
}
showAlertDialog(BuildContext context, String alertTitle, String alertMessage) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
title: Center(child: Text(alertTitle)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
alertMessage,
textAlign: TextAlign.center,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FlatButton(
child: Center(
child: Text(
'Ok',
textAlign: TextAlign.center,
)),
onPressed: () {
Navigator.of(context).pop();
// Navigator.of(context).push(MaterialPageRoute(
// builder: (BuildContext context) {
// return Home();//Intead of giving Home() anything can be passed here
// }));
},
),
])
],
),
);
});
}
}
現在我一直關閉對話框,但我想導航到另一個 class。
傳遞 class 名稱是個壞主意 - class 可能需要構造函數的參數,它不是類型安全的,並且需要反射,而 Flutter 不支持。
您可以改為傳遞 function ,它將創建所需類型的小部件:
showAlertDialog(
BuildContext context,
String alertTitle,
String alertMessage,
Widget Function() createPage,
) {
// ...
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) {
return createPage();
}));
},
// ...
}
並像這樣稱呼它:
showAlertDialog(context, title, message, () => Home())
謝謝。 我正是在尋找這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.