Сделайте вложенные виджеты отзывчивыми в Flutter

#flutter #responsive-design #overflow

Вопрос:

Для простоты у меня есть а Container , и его ребенок-а Column . В Column виджете есть еще два Container . Теперь корень Container реагирует и изменяет размер в соответствии с экраном, но его дочерний элемент, который находится Container внутри Column , не изменяет размер и, таким образом, дает мне переполнение рендеринга. Ручная настройка MediaQuery.of(context).size всех дочерних виджетов не кажется оптимальной.

Код,

 Scaffold(
      body: Container(
        height: size.height * 0.3, //size = MediaQuery.of(context).size
        width: size.width * 0.3,
        color: Colors.pinkAccent,
        child: Column(
          children: [
            Container(
              color: Colors.greenAccent,
              height: 100,
              width: 100,
            ),
            Container(
              height: 100,
              width: 100,
              color: Colors.orangeAccent,
            ),
          ],
        ),
      ),
    );
 

введите описание изображения здесь

Я хочу изменить размер дочернего Container элемента вместе с родителем Container .

Ответ №1:

Если я правильно понял вашу проблему, вы можете достичь своей цели, используя Flexible Widget все, что вам Container нужно:

 class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      body: Container(
        height: size.height * 0.3, //size = MediaQuery.of(context).size
        width: size.width * 0.3,
        color: Colors.pinkAccent,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Flexible(
              flex: 1,
              child: Container(
                color: Colors.greenAccent,
                width: 100,
                child: Text('This is a text. This is a text. This is a text. This is a text. '),
              ),
            ),
            Flexible(
              flex: 1,
              child: Container(
                width: 100,
                color: Colors.orangeAccent,
                child: Text('This is a text. This is a text. This is a text. This is a text. '),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
 

Вы можете настроить, сколько места занимает каждый Container из них внутри Flexible Widget , изменив flex свойство в каждом из них.