如何根据不同的屏幕尺寸添加padding或margin

A k*_*har 3 responsive-design dart flutter responsive

我想根据屏幕尺寸提供填充或边距。

下面是具有相同填充的两个不同尺寸屏幕的代码和图像。

这是我的代码:

    Padding(
            padding: const EdgeInsets.only(top: 160, left: 90, bottom: 20),
            child: Row(
              children: <Widget>[
                Image.asset(
                  'assets/logo.png',
                  height: 70,
                  width: 70,
                ),
                Text(
                  '  Whatsapp',
                  style: TextStyle(
                    fontSize: 26,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
Run Code Online (Sandbox Code Playgroud)

我的真实设备

在此处输入图片说明

Android Studio 模拟器

在此处输入图片说明

Bre*_*dan 6

您可以创建两个接受 BuildContext 的方法

double deviceHeight(BuildContext context) => MediaQuery.of(context).size.height;

double deviceWidth(BuildContext context) => MediaQuery.of(context).size.width;
Run Code Online (Sandbox Code Playgroud)

如果您想要统一的边距,无论设备宽度或高度如何,请像这样使用

Padding(
        padding: EdgeInsets.only(
          top: deviceHeight(context) * 0.3,
          left: deviceWidth(context) * 0.09,
          bottom: deviceHeight(context) * 0.06,
        ),
        child: Row(
          children: <Widget>[
            Image.asset(
              'assets/logo.png',
              height: 70,
              width: 70,
            ),
            Text(
              '  Whatsapp',
              style: TextStyle(
                fontSize: 26,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
Run Code Online (Sandbox Code Playgroud)

deviceHeight(context) * 0.3只是表示屏幕高度的 30%,deviceWidth(context) * 0.09表示屏幕宽度的 9%,bottom: deviceHeight(context) * 0.06表示屏幕高度的 6%

这样做的优点是您可以调整数字以匹配,并且在任何设备上都将采用相同的间距。

  • 请注意,您不能在 const 表达式中使用上述内容。例如: `const Container(height: deviceHeight(context) * 0.6, child: Text("Hello World!"),);` 这将导致错误。因为该函数的值在编译期间无法确定。 (2认同)

小智 5

您可以MediaQuery.of(context).size.height用来获取屏幕的高度和屏幕的MediaQuery.of(context).size.width宽度。

根据您的图像,最好使用ExpandedSpacer、等 Flex 小部件Flexible来调整 Column 内小部件之间的间距。