Home > Back-end >  Flutter, How to fit width in Column to first child
Flutter, How to fit width in Column to first child

Time:12-04

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

CodePudding user response:

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