【问题标题】:Row mainAxisAlignment not working with FittedBox行 mainAxisAlignment 不适用于 FittedBox
【发布时间】:2021-09-17 21:38:00
【问题描述】:

使用 FittedBox 包装后行 mainAxisAlignment 不起作用 请解释一下为什么会这样。

Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          height: 20,
          child: FittedBox(
            fit: BoxFit.fill,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Text('THis is the thing'),
                Text('THis is another thing'),
              ],
            ),
          ),
        )
    );
  }

预期

输出

【问题讨论】:

  • 只要删除FittedBox,你为什么需要那个?
  • 我正在使用可变长度的字符串,我需要将该字符串放入框中。

标签: flutter dart flutter-layout


【解决方案1】:

如果您真的想在 FittedBox 中使用 Row 并具有 mainAxisAllignment.spaceBetween 或任何效果,则必须使用 SizedBox 手动设置 spaceBetween 并根据间距宽度。还将 fit 属性设置为 BoxFit.fitHeight

Container(
          height: 20,
            child: FittedBox(
              alignment: Alignment.center,
              fit: BoxFit.fitHeight,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('THis is the thing',style: TextStyle(fontSize: 20),),
                  SizedBox(width: 300,),
                  Text('THis is another thing',style: TextStyle(fontSize: 20,),),
                ],
              ),
            ),
        )

注意:设置 allignment 属性来指定定位。对于MainAxisAllignment.startMainAxisAllignment.start。 例如:Alignment.topLeft 得到MainAxisAllignment.start 效果。

【讨论】:

  • 好吧,看来 SizedBox 是唯一的解决方案。
【解决方案2】:

回答你的问题,

mainAxisAlignment 行在用FittedBox 包装后不起作用 请解释一下为什么会这样。

Container 总是填满屏幕大小的整个宽度。如果它有孩子,那么它将自己包裹起来以匹配其孩子的宽度。

另一个有趣的小部件FittedBox 将根据可用空间缩放来适应其子代的大小。

解决方案

为了达到预期的效果,您可以将Container小部件的width强制设置为double.infinity

片段

body: Container(
          height: 20,
          width: double.infinity,
          child: FittedBox(
            fit: BoxFit.fill,
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [Text('THis is the ROW'), Text('THis is another  ')],
            ),
          ),
        )

注意:如果文本很小,它将被放大以占据其余空间,因为它位于 FittedBox 内,反之亦然。

【讨论】:

  • 抱歉,Row 中仍然不支持 spaceBetween,结果没有改善
  • 如果您需要在文本之间留一个空格,请将您的 Row 小部件放在 FittedBox 之外。
猜你喜欢
  • 2021-05-22
  • 2021-06-13
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2022-08-04
相关资源
最近更新 更多