0

There are two items in Column. Column must be "wrap content" (does not fill all available width). First item in column must fill space.

How to achieve this? screenshot

My code now:

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)),
              ]),
        ),
      ),
    );
  }
}

When I add crossAxisAlignment: CrossAxisAlignment.stretch to Column, then it cause stretching on all screen width instead just fit available width (see arrow on screenshot).

Nickolay Savchenko
  • 1,474
  • 16
  • 28
  • Instead of an `_item` Widget function, you should prefer a Widget class. Check this thread for the benefits of using Widget classes: https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-reusable-widgets – Thierry Feb 05 '21 at 21:30
  • @Thierry in this case _item function will work absolutely in same way as separate stateless widget Item. In two cases item will rebuild when parent MyHomePage build called – Nickolay Savchenko Feb 05 '21 at 22:42
  • For more complex or stateful elements separate widget really should be prefer – Nickolay Savchenko Feb 05 '21 at 22:44

1 Answers1

1

After experiments with Flexible, LayoutBuilder, FittedBox I found this solution using IntrinsicWidth in combination with CrossAxisAlignment.stretch

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)),
                ]),
          )
Nickolay Savchenko
  • 1,474
  • 16
  • 28