Flutter, How to fit width in Column to first child

Viewed 793

This is my code .

 ConstrainedBox(
      constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.5),
      child: (message.caption != null)
          ?  Column(
                children: [
                  Flexible(
                    child: ImageLoader(message: message, controller: _),
                  ),
                   Container(
                    child: Padding(
                      padding: const EdgeInsets.only(top: 8.0),
                      child: BubbleText(
                          message: message,
                          fromCaption: true,
                          account: account),
                    ),
                  ),
                ],
              
          )
          : ...

This is what my column looks like with 2 children

s

Here is how I want it to look

s

2 Answers

if you want to dynamic width you must use statefull widget, because you have storing first child width. So below code will works for your sitution

class Challenge extends StatefulWidget {
  const Challenge({Key? key}) : super(key: key);

  @override
  _ChallengeState createState() => _ChallengeState();
}

class _ChallengeState extends State<Challenge> {
  final GlobalKey _firstChildKey = GlobalKey();
  double? childWidth;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final RenderBox renderBoxRed = _firstChildKey.currentContext.findRenderObject();
      final size = renderBoxRed.size;
      setState(() {
        childWidth = size.width;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return ConstrainedBox(
        constraints: BoxConstraints(maxHeight: size.height * 0.5, maxWidth: childWidth ?? size.width * .2),
        child: Column(
          children: [
            Flexible(
              key: _firstChildKey,
              child: ImageLoader(message: message, controller: _),
            ),
            Container(
              child: Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: BubbleText(message: message, fromCaption: true, account: account),
              ),
            ),
          ],
        ));
  }
}

It actually amazes me how often does this need arise and how no one has wrote a package about this yet.

So I did: https://pub.dev/packages/flex_with_main_child

It'll look something like this:

ColumnWithMainChild(
  mainChild: Flexible(
    child: ImageLoader(message: message, controller: _),
  ),
  childrenBelow: [
    Container(
      child: Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: BubbleText(
            message: message,
            fromCaption: true,
            account: account),
      ),
    ),
  ],
)
Related