首页 > 解决方案 > 如何在 Column 中对齐 Widget?

问题描述

我想将我的按钮向右对齐。现在,我正在使用在下面的示例中mainAxisAlignment设置为MainAxisAlignment.endlike 的 Row 来完成它。然而,这似乎不是一个好方法,因为它有很多代码,我不认为这是这样做的方式。

我已经尝试过这个Align小部件,但这不起作用。我猜是因为它没有扩展内部小部件,因此Alignment.centerRight什么也不做。

我现在使用的代码:

new Row(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisAlignment: MainAxisAlignment.end,
  children: <Widget>[
    new FlatButton(
          onPressed: _navigateToPreparationStepsWidgetClicked,
          child: new Row(
            children: <Widget>[
              new Text(
                'View Preparation Steps'.toUpperCase(),
                style: new TextStyle(
                    fontWeight: FontWeight.bold),
              ),
              new Icon(Icons.keyboard_arrow_right)
            ],
          ))
  ],
)

Button在例如 a中对齐例如 a 的正确方法是Column什么?

标签: flutterdartalignment

解决方案


仔细观察,这是因为您的按钮中有一行。默认情况下,一行会展开以占用尽可能多的空间。因此,当您将按钮向右对齐时,它正在执行此操作,但按钮本身占据了整行。如果你改变颜色,你会更容易看到。简单的答案是在按钮的行上将 mainAxisSize 设置为 MainAxisSize.min。

这对我来说就像预期的那样工作:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(),
        body: Column(
          children: <Widget>[
            FlatButton(child: Text("Default"), color: Colors.blue, onPressed: () {}),
            Align(
              child: FlatButton(child: Text("Left"), color: Colors.red, onPressed: () {}),
              alignment: Alignment.centerLeft,
            ),
            Center(child: FlatButton(child: Text("Centered"), color: Colors.orange, onPressed: () {})),
            Align(
              child: FlatButton(child: Text("Right"), color: Colors.green, onPressed: () {}),
              alignment: Alignment.centerRight,
            ),
            Align(
              child: new FlatButton(
                onPressed: () {},
                child: new Row(
                  children: <Widget>[
                    new Text(
                      'View Preparation Steps'.toUpperCase(),
                      style: new TextStyle(fontWeight: FontWeight.bold),
                    ),
                    new Icon(Icons.keyboard_arrow_right)
                  ],
                  mainAxisSize: MainAxisSize.min,
                ),
              ),
              alignment: Alignment.centerRight,
            ),
          ],
        ),
      ),
    );
  }
}

结果是:

具有对齐项目的列的屏幕截图


推荐阅读