【问题标题】:Container fills the screen even when I specify `width` and `height`即使我指定“宽度”和“高度”,容器也会填满屏幕
【发布时间】:2021-05-26 13:36:49
【问题描述】:

我正在做一个颤振项目,我想在另一个具有特定尺寸的项目中显示Container。但是,当我指定Containers 的大小时,它并没有考虑到它。

这是一个代码示例:

import 'package:flutter/material.dart';

void main() {
  runApp(MyWidget());
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200.0,
      height: 200.0,
      color: Colors.blue,
      child: Container(
        width: 20.0,
        height: 20.0,
        color: Colors.red,
      ),
    );
  }
}

这是我得到的,我看不到蓝色的Container

发生了什么,我该怎么办?

【问题讨论】:

标签: flutter dart containers flutter-container


【解决方案1】:

正如我在评论中提到的,您需要指定第二个框的位置

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200.0,
      height: 200.0,
      color: Colors.blue,
      alignment: Alignment.center,
      child: Container(
        width: 20.0,
        height: 20.0,
        color: Colors.red,
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    您需要指定第二个框的位置

       Container(
            width: 200.0,
            height: 200.0,
            color: Colors.orange,
            alignment: Alignment.center, // where to position the child
            child: Container(
              width: 50.0,
              height: 50.0,
              color: Colors.blue,
            ),
          ),
    

    【讨论】:

      【解决方案3】:

      实际上,这里发生的是您直接将Container 作为根小部件传递。因此,容器必须占据整个屏幕,因为它不知道在后台还显示什么。所以,你会看到它占据了整个屏幕。对于红色容器,它似乎也遵循与其父容器相同的属性。所以,它填满了整个屏幕。除非,我们指定 alignment 属性。

      我也将对齐属性添加到父级。然而,它仍然占据了整个屏幕。

      import 'package:flutter/material.dart';
      
      void main() {
        runApp(MyWidget());
      }
      
      class MyWidget extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return Container(
            alignment: Alignment.center,
            width: 40.0,
            height: 40.0,
            color: Colors.blue,
            child: Container(
              alignment: Alignment.center,
              width: 20.0,
              height: 20.0,
              color: Colors.red,
            ),
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2012-11-30
        • 2012-04-02
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多