首页 > 解决方案 > 如何在 Flutter 中将 AlertDialog FlatButton 居中

问题描述

如何在无需创建自定义 AlertDialog 的情况下将 FlatButton 设置为居中对齐?

AlertDialog(
      title: Text(
        'Alert Dialog'.toUpperCase(),
        textAlign: TextAlign.center,
        style: TextStyle(fontWeight: FontWeight.bold, fontSize: 28.0),
      ),
      content: SingleChildScrollView(
        child: ListBody(
          children: <Widget>[
            Text('Scrollable AlertDialog' * 100),
          ],
        ),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text(
            'Accept'.toUpperCase(),
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );

这是它的样子

我尝试删除“操作”并将 FlatButton 添加到“内容”的一行中,但滚动停止工作并且内容溢出。

content: Column(
        children: <Widget>[
          SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text('Scrollable AlertDialog.' * 50),
              ],
            ),
          ),
          Row(
            children: <Widget>[
              FlatButton(
                child: Text(
                  'Accept'.toUpperCase(),
                  style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0
                  ),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        ],
      ),

标签: flutterflutter-alertdialog

解决方案


谷歌的材料设计指南不希望你把它放在中心,这就是为什么 Flutter 团队使用ButtonBar并且actions你无法控制属性ButtonBar内部的对齐actions,所以如果你真的想将你的单个按钮居中,有 2 个简单的解决方法:

  1. 在源代码中进行更改,在dialog.dart' AlertDialogsbuild方法中,您会看到一个ButtonBar, 小部件,添加alignment到它。

    ButtonBar(
      alignment: MainAxisAlignment.center, // add this line 
      // ...
    ) 
    
  2. 您可以使用类似的虚拟小部件SizedBox并为其提供一些宽度。

    actions: [
      SizedBox(width: space),
      FlatButton(
        onPressed: () {},
        child: Text('Button'),
      ),
      SizedBox(width: space),
    ]
    

截屏:

在此处输入图像描述


推荐阅读