Flutter容器溢出

3

我想在具有响应式宽度和高度的容器内显示图像。

以下是我的代码:

 ...
 child: Column (
    mainAxisSize: MainAxisSize.min,
    children: [
       Row (
          children: [
             Padding (
                padding: EdgeInsets.all(20),
                child: Container(
                   height: MediaQuery.of(context).size.height *.3,
                   width: MediaQuery.of(context).size.width * 1,
                   padding: const EdgeInsets.all(15),
                   decoration: BoxDecoration(
                      image: DecorationImage(
                         image: AssetImage("assets/images/gunung.jpg"),
                         fit: BoxFit.cover,
                ...

这是输出结果:

在此输入图片描述

有没有解决方案?


我建议使用一个包来设置尺寸,这样你就不用担心它了。像Flutter Utils或Sizer这样的包可以自动调整每个方向上的尺寸。但如果你不想用它,可以尝试使用Layout Builder,如果屏幕是横向的,你可以在上面设置自己的尺寸。 - Arbiter Chil
我尝试使用Sizer,但是出现了“LateInitializationError:未初始化字段'height'”的错误。 - aufa
@ArbiterChil,对于Flutter的基础知识,您不需要使用任何包。如果您不需要使用包,那么使用包只会增加您的应用程序依赖和大小。 - kartoon
2个回答

5

只需将此更改为您的代码:

//添加 扩展小部件


 child: Column (
        mainAxisSize: MainAxisSize.min,
        children: [
           Row (
              children: [
    //Add Expanded Widget it will solve your issue 
    Expanded(
                 Padding (
                    padding: EdgeInsets.all(20),
                    child: Container(
                       height: MediaQuery.of(context).size.height *.3,
                       width: MediaQuery.of(context).size.width * 1,
                       padding: const EdgeInsets.all(15),
                       decoration: BoxDecoration(
                          image: DecorationImage(
                             image: AssetImage("assets/images/gunung.jpg"),
                             fit: BoxFit.cover,

这个有效,谢谢。 - aufa

0

由于您将Containerwidth设置为

MediaQuery.of(context).size.width * 1

这意味着它将占据您设备屏幕的宽度空间。

更不用说,您还设置了 Padding。这将占据左、上、右和下方的 20 个间距。

padding: EdgeInsets.all(20)

这个Padding使得你的Container超出了必要的范围,因此发生了溢出。

有许多方法可以解决这个问题。

  1. 您可以从您为容器初始化的宽度中减去填充。从左边减去20,从右边减去20。
(MediaQuery.of(context).size.width * 1) - 20 - 20
  1. 您可以在容器本身中设置填充。您可能不需要单独使用 Padding 小部件悬挂在 Container 上方。
    Padding(                                  // <---- remove
      padding: EdgeInsets.all(20),            // <---- remove
      child: Container(
        height: MediaQuery.of(context).size.height *.3,
        width: MediaQuery.of(context).size.width * 1,
        padding: const EdgeInsets.all(20),    // <---- use this
        ...

关于容器周围的填充怎么办?尝试使用边距但它溢出了。 - aufa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接