【问题标题】:Is it possible to pass class as a parameter in a function in Flutter?是否可以在 Flutter 的函数中将类作为参数传递?
【发布时间】:2020-02-19 15:58:18
【问题描述】:

在这里,我有一个实用程序类,其中我有一个显示对话框的函数,所以我正在尝试制作一个可以在整个项目的任何地方使用的 AlertDialog 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  
//                          }));
                        },
                      ),
                    ])
              ],
            ),
          );
        });
  }
}

现在我一直在关闭对话框,但我想在那里导航到另一个类。

【问题讨论】:

    标签: flutter utility-method flutter-alertdialog


    【解决方案1】:

    传递类名是个坏主意——类可能需要构造函数的参数,它不是类型安全的,而且它需要反射,而 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())
    

    【讨论】:

    • 很有帮助,我也在找一样的
    猜你喜欢
    • 2014-04-15
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2012-06-05
    相关资源
    最近更新 更多