Flutter,如何使列中的宽度适合第一个 child

Flutter, How to fit width in Column to first child

这是我的代码。

 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),
                    ),
                  ),
                ],
              
          )
          : ...

这是我的专栏 2 children

的样子

这是我想要的样子

如果你想要动态宽度,你必须使用有状态的小部件,因为你已经存储了第一个子宽度。所以下面的代码将适用于您的情况

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

我真的很惊讶这种需求出现的频率有多高,而且还没有人为此写过一个包。

所以我做了:https://pub.dev/packages/flex_with_main_child

看起来像这样:

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