颤动的屏幕尺寸

问题描述 投票:15回答:2

我在flutter上创建了一个新的应用程序,在不同设备之间切换时我遇到了屏幕尺寸问题。

我使用Pixel 2XL屏幕尺寸创建了应用程序,因为我有容器和ListView的子容器,它要求我包含容器的高度和宽度。

因此,当我将设备切换到新设备时,容器太长并且抛出错误。

我该如何制作它以便应用程序针对所有屏幕进行优化?

dart screen flutter screen-size
2个回答
73
投票

您可以使用:

  • double width = MediaQuery.of(context).size.width;
  • double height = MediaQuery.of(context).size.height;

1
投票

MediaQuery.of(context).size.widthMediaQuery.of(context).size.height效果很好,但每次都需要写宽度/ 20这样的表达式来设置特定的高度宽度。

我在flutter上创建了一个新的应用程序,在不同设备之间切换时我遇到了屏幕尺寸问题。

是的,flutter_screenutil plugin可用于调整屏幕和字体大小。让您的UI在不同的屏幕尺寸上显示合理的布局!

用法:

添加依赖:

安装前请检查最新版本。

dependencies:
  flutter:
    sdk: flutter
  # add flutter_ScreenUtil
  flutter_screenutil: ^0.4.2

将以下导入添加到Dart代码:

import 'package:flutter_screenutil/flutter_screenutil.dart';

初始化并设置拟合大小和字体大小,以根据系统的“字体大小”辅助功能选项进行缩放

//fill in the screen size of the device in the design

//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);

//If the design is based on the size of the iPhone6 ​​(iPhone6 ​​750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);

使用:

//for example:
//rectangle
Container(
           width: ScreenUtil().setWidth(375),
           height: ScreenUtil().setHeight(200),
           ...
            ),

////If you want to display a square:
Container(
           width: ScreenUtil().setWidth(300),
           height: ScreenUtil().setWidth(300),
            ),

有关更多详细信息,请参阅更新的documentation

注意:我测试并使用了这个插件,它适用于包括iPad在内的所有设备

希望这会对某人有所帮助


1
投票

获得width很容易,但height可能很棘手,以下是处理height的方法

// full screen width and height
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;

// height without SafeArea
var padding = MediaQuery.of(context).padding;
double height1 = height - padding.top - padding.bottom;

// height without status bar
double height2 = height - padding.top;

// height without status and toolbar
double height3 = height - padding.top - kToolbarHeight;
© www.soinside.com 2019 - 2024. All rights reserved.