【问题标题】:Expand multiple widgets to full width in a row in Flutter?在 Flutter 中连续将多个小部件扩展到全宽?
【发布时间】:2020-01-16 05:05:15
【问题描述】:

我正在尝试让 Flutter 中的按钮扩展到其父宽度,并随着更多小部件的添加而动态扩展。例如,如果一行中有两个按钮,它们将分别扩展为 50% 宽度,三个按钮扩展为 33% 等。

我尝试了width: Double.infinite,它适用于单个按钮。可以理解的是,这不适用于多个按钮,因为宽度不受限制并且 Flutter 不知道如何调整元素的大小。

我尝试了各种属性,SizedBoxcrossAxisAlignmentExpanded,但它们似乎不起作用。

我想要实现的目标类似于:https://bulma.io/documentation/columns/basics/ - 基于 flex 的列布局。

App.dart

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      // theme: WhisperyTheme,
      // theme: ThemeData(fontFamily: "Overpass"),
      home: Scaffold(
        body: Center(
          child: Column(
            children: <Widget>[
              LongButton(
                onTap: () => null,
                text: "Primary Button",
              ),
              Row(
                children: <Widget>[
                  LongButton(
                    onTap: () => null,
                    text: "Secondary Button",
                  ),
                  LongButton(
                    onTap: () => null,
                    text: "Secondary Button",
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

Button.dart

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(maxHeight: 40.0),
      margin: EdgeInsets.all(15),
      height: 40.0,
      decoration: BoxDecoration(border: Border.all(width: 1.5)),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _onTap,
          child: Center(
            child: Text(_text),
          ),
        ),
      ),
    );
  }

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你可以用Flexible小部件包裹你的按钮,它的默认flex参数是1,所以空间将在所有小部件之间平均分配:

    Row(
      children: <Widget>[
        Flexible(
          child: LongButton(
            onTap: () => null,
            text: 'Secondary Button',
          ),
        ),
        Flexible(
          child: LongButton(
            onTap: () => null,
            text: 'Secondary Button',
          ),
        ),
      ],
    )
    

    【讨论】:

    • 另外,不要忘记将 Flexible 的 fit 参数设置为 FlexFit.tight。
    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2020-05-24
    • 2020-09-06
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多