如何在列中对齐小部件?

Jen*_*ens 2 alignment dart flutter

我想将我的按钮向右对齐。现在,我正在使用在下面的示例中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)
            ],
          ))
  ],
)
Run Code Online (Sandbox Code Playgroud)

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

rmt*_*zie 5

仔细检查,这是因为您的按钮中有一行。默认情况下,一行会扩展以占用尽可能多的空间。因此,当您将按钮向右对齐时,它正在这样做,但按钮本身占据了整行。如果你改变了颜色,你会更容易看到。简单的答案是在按钮的行上将 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,
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

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