0

I have the following layout

  Container(
    color: Colors.red,
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text(
            'You have pushed the button this many times:',
          ),
        Container(
          color: Colors.blue,
          child: const Text(
            'You have pushed the',
          ),
        ),
      ],
    ),
  ),

I would like the nested Container (the one with the blue background) the have at least the width of the parent Container.

Using double.infinity does not do the job, since it will stretch the width to the whole available width on the screen.

Thank you

Edit: So the only answer that worked for me was this one https://stackoverflow.com/a/64874106/3808307 (using the width instead of the height). I wonder if there is a way to achieve it without having to have post frame callback

user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

0

The container here takes the width of the child which is Text. You can wrap the Text with a widget that takes the full width such as Center (or Align if you prefer different alignment)

    Container(
      color: Colors.red,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text(
            'You have pushed the button this many times:',
          ),
          Container(
            color: Colors.blue,            
            child: const Center( // <~~~~~ or `Align`
              child: Text(
                'You have pushed the',
              ),
            ),
          ),
        ],
      ),
    );

This should make the blue background takes the full width of the parent Container.

Though this also means that both the Column and the parent Container will take the full available width. Previously, the parent container was taken the width of the top Text widget (i.e. 'You have pushed the button this many times:').

This may not be the ideal (readable/obvious) approach, but it's all I can think of now.

osaxma
  • 2,657
  • 2
  • 12
  • 21
  • Hi, thank you, it doesn't work. It does not take the full width of the parent. The nested container still takes the width of the content. And it does widen the parent, which I don't want – user3808307 Feb 15 '22 at 23:51
  • @user3808307 It's working here: https://dartpad.dev/?id=ca553e987d44656de6cb344b5cb772e5 .. It'll sure widen the parent, you need to specify the constraint for the parent. It's not possible to have it both ways. – osaxma Feb 15 '22 at 23:55
  • Here https://dartpad.dartlang.org/?id=e75b493dae1287757c5e1d77a0dc73f1 it doesn't. Either way, if I need to constraint the parent it's no good. The parent needs to be as wide as the text, and the text wraps if it is longer than the parent – user3808307 Feb 16 '22 at 00:17
  • your example doesn't have the column – user3808307 Feb 16 '22 at 00:18