代码之家  ›  专栏  ›  技术社区  ›  Nickolay Savchenko

如何在Flatter中填充父窗口小部件宽度,但防止在所有可用空间上拉伸父窗口小部件

  •  0
  • Nickolay Savchenko  · 技术社区  · 5 年前

    列中有两项。列必须为“包裹内容”(不填充所有可用宽度)。列中的第一项必须填充空格。

    如何做到这一点? screenshot

    我现在的代码是:

    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: ListView(children: [
          _item(context, '123456', '123456789000000'),
          _item(context, '1234567890000000', '1234567')
        ]));
      }
    
      Widget _item(BuildContext context, String firstLine, String secondLine) {
        final theme = Theme.of(context);
        return Container(
          alignment: Alignment.topLeft,
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: ColoredBox(
              color: Colors.black12,
              child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container( // This container's width must be not less than container below
                        color: Colors.blueGrey,
                        child: Text(firstLine, style: theme.textTheme.headline4)),
                    Container(
                        color: Colors.cyan,
                        child: Text(secondLine, style: theme.textTheme.headline4)),
                  ]),
            ),
          ),
        );
      }
    }
    

    当我加上 crossAxisAlignment: CrossAxisAlignment.stretch 到列,则会导致所有屏幕宽度的拉伸,而不是仅适合可用宽度(请参见屏幕截图上的箭头)。

    0 回复  |  直到 5 年前
        1
  •  1
  •   Nickolay Savchenko    5 年前

    在使用Flexible、LayoutBuilder和FittedBox进行实验后,我发现了使用IntrinsicWidth与CrossAxisAlignment相结合的解决方案。伸展

    IntrinsicWidth(
                child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Container( // This container's width must be not less than container below
                          color: Colors.blueGrey,
                          child: Text(firstLine, style: theme.textTheme.headline4)),
                      Container(
                          color: Colors.cyan,
                          child: Text(secondLine, style: theme.textTheme.headline4)),
                    ]),
              )