是否可以将类作为参数传递给函数?

时间:2019-10-23 11:51:31

标签: flutter utility-method flutter-alertdialog

在这里,我有一个实用工具类,其中有用于显示DialogBox的函数,因此,我试图制作一个AlertDailog Box,可以在整个项目中使用它。 因此,我已将标题,描述作为参数传递,并且还希望传递类名称,以便在按下警报对话框中的按钮时,我们可以导航到该屏幕

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  
//                          }));
                        },
                      ),
                    ])
              ],
            ),
          );
        });
  }
}

现在我一直保持关闭对话框的状态,但是我想在那里导航到其他课程

1 个答案:

答案 0 :(得分:3)

传递类名是一个坏主意–类可能需要构造函数的参数,它的类型安全,并且需要反射,而Flutter不支持。

您可以改为传递一个函数,该函数将创建所需类型的小部件:

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())