如何在flutter中创建自定义Dialog

S M*_*han 4 dialog flutter

我想创建一个自定义对话框,如下所示。我可以创建一个带有两个按钮(正按钮和负按钮)的普通对话框。但是我搜索了很多关于创建自定义对话框(如下所示)的信息,但没有成功。

在此输入图像描述

showAlertDialog(BuildContext context) {

    // set up the buttons
    Widget cancelButton = FlatButton(
      child: Text("Cancel"),
      onPressed:  () {},
    );
    Widget continueButton = FlatButton(
      child: Text("Continue"),
      onPressed:  () {},
    );

    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      title: Text("Action"),
      content: Text("Would you like to continue learning how to use Flutter alerts?"),
      actions: [
        cancelButton,
        continueButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
Run Code Online (Sandbox Code Playgroud)

现在我希望将这些按钮和图像作为对话框的子项,并使用底部的图标按钮“X”来关闭对话框。任何帮助表示赞赏。我是颤振的完全初学者。

jit*_*555 7

为此,我们创建一个自定义对话框

1.自定义对话框内容类

class CustomDialog extends StatelessWidget {

  dialogContent(BuildContext context) {
    return Container(
      decoration: new BoxDecoration(
        color: Colors.white,
        shape: BoxShape.rectangle,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.black26,
            blurRadius: 10.0,
            offset: const Offset(0.0, 10.0),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min, // To make the card compact
        children: <Widget>[
          Image.asset('assets/images/image.jpg', height: 100),
          Text(
            "Text 1",
            style: TextStyle(
              fontSize: 24.0,
              fontWeight: FontWeight.w700,
            ),
          ),
          SizedBox(height: 16.0),
          Text(
            "Text 1",
            style: TextStyle(
              fontSize: 24.0,
              fontWeight: FontWeight.w700,
            ),
          ),
          SizedBox(height: 24.0),
          Align(
            alignment: Alignment.bottomCenter,
            child: Icon(Icons.cancel),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
      elevation: 0.0,
      backgroundColor: Colors.transparent,
      child: dialogContent(context),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

2. 单击时调用自定义对话框:

RaisedButton(
            color: Colors.redAccent,
            textColor: Colors.white,
            onPressed: () {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return CustomDialog();
                  });
              ;
            },
            child: Text("PressMe"),
          ),
Run Code Online (Sandbox Code Playgroud)

  • @SM Vaidhyanathan:如果答案对你有用,你能接受吗?以便其他人可以参考此内容。 (2认同)