Flutter, как подогнать ширину столбца к первому дочернему элементу

#flutter #flutter-layout #containers

#flutter #flutter-layout #контейнеры

Вопрос:

Это мой код.

  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 дочерними элементами

s

Вот как я хочу, чтобы это выглядело

s

Комментарии:

1. дайте им отступы или вы также можете использовать для этого затраченный виджет

Ответ №1:

если вы хотите динамическую ширину, вы должны использовать виджет с полным состоянием, потому что у вас есть сохранение первой дочерней ширины. Итак, приведенный ниже код будет работать для вашей ситуации

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

Комментарии:

1. Я впервые задаю вопрос, и ваш ответ был очень правильным и очень быстрым, большое вам спасибо.

Ответ №2:

Меня действительно поражает, как часто возникает такая необходимость и как никто еще не написал пакет об этом.

Итак, я сделал: 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),
      ),
    ),
  ],
)
 

Комментарии:

1. Вы потрясающие, спасибо!!