首页 > 解决方案 > 如何在颤动的容器内制作固定大小的容器

问题描述

我正在尝试制作应用程序的布局,其中主容器将具有 45% 的设备高度,并且主容器内的容器应该是固定大小。

我编写了以下代码,但内部容器将全高作为其父(主)容器。

class TestContainer extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          width: 50,
          height:MediaQuery.of(context).size.height * 0.45,
          color: Colors.red
          child:Container(
          width: 50,
          height: 100,
          color: Colors.green
          )
        );
      }
    }

任何线索我做错了什么?

标签: flutterdartflutter-layout

解决方案


通过用Center小部件包装它来修复它:

class TestContainer extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          width: 50,
          height:MediaQuery.of(context).size.height * 0.45,
          color: Colors.red,
          // wrap with a center widget
          child:Center(
            child: Container(
            width: 50,
            height: 100,
            color: Colors.green
            ),
          )
        );
      }
    }

将内容器放置在底部中心

class TestContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 50,
      height: MediaQuery.of(context).size.height * 0.45,
      color: Colors.red,
      // wrap with a align widget
      child: Align(
        // set the alignment property
        alignment: Alignment.bottomCenter,
        child: Container(
          width: 50,
          height: 100,
          color: Colors.green,
        ),
      ),
    );
  }
}

在此处阅读有关 Flutter 中布局约束的更多信息:https ://flutter.dev/docs/development/ui/layout/constraints


推荐阅读