首页 > 解决方案 > 在 Flutter 中使嵌套的小部件具有响应性

问题描述

为简单起见,我有 a Container,它的孩子是 a 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

标签: flutterresponsive-designoverflow

解决方案


如果我正确理解了您的问题,您可以使用Flexible Widget围绕您Container的 s 来实现您的目标:

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


推荐阅读