如何在颤振容器内部制作固定大小的容器

时间:2020-08-07 18:46:17

标签: flutter dart flutter-layout

我正在尝试对应用程序进行布局,使主容器占设备高度的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
          )
        );
      }
    }

任何线索我在做什么错吗?

3 个答案:

答案 0 :(得分:1)

通过使用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

答案 1 :(得分:0)

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:Stack(
  children: <Widget>[
      Positioned(
        bottom: 0,
        child: Container(
                width: 50,
                height: 100,
                color: Colors.green
                )
             )
           ] )
      ); }
}

答案 2 :(得分:0)

Flutter Container 的基本属性是消耗父级大小...因此,为了将 Container 作为子级添加到另一个 Container 中,您只需指定需要显示内部容器的位置在外容器上.. otherwise the child container will grow to the size of its parent Container.

Container(
    width: 400.0,
    height: 400.0,
    color: Colors.green,
    alignment: Alignment.center, // align your child's position.
    child: Container(
      width: 100.0,
      height: 100.0,
      color: Colors.red,
    ),
  ),