且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使Flutter应用根据不同的屏幕尺寸做出响应?

更新时间:2023-01-24 15:33:18

使用 MediaQuery 类:

Using MediaQuery class:

MediaQueryData queryData;
queryData = MediaQuery.of(context);




MediaQuery :建立一个子树,其中媒体查询将
解析为给定数据。

MediaQuery: Establishes a subtree in which media queries resolve to the given data.

MediaQueryData :有关某种媒体的信息(例如, ,一个
窗口)。

MediaQueryData: Information about a piece of media (e.g., a window).

获取设备像素比率:

queryData.devicePixelRatio

获取宽度和高度设备屏幕:

To get width and height of the device screen:

queryData.size.width
queryData.size.height

要获取文本比例因子:

queryData.textScaleFactor

使用 AspectRatio 类:

来自doc:


一个试图将孩子的尺寸调整为

A widget that attempts to size the child to a specific aspect ratio.

窗口小部件首先尝试布局
约束所允许的最大宽度。小部件的高度是通过将给定的宽高比
应用于宽度来确定的,表示为宽度与
高度的比率。

The widget first tries the largest width permitted by the layout constraints. The height of the widget is determined by applying the given aspect ratio to the width, expressed as a ratio of width to height.

例如,宽高比为16:9的宽高比的值将为
16.0 / 9.0。如果最大宽度是无限的,则通过将宽高比应用于最大高度来确定初始宽度。

For example, a 16:9 width:height aspect ratio would have a value of 16.0/9.0. If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height.

现在考虑第二个示例,这次的长宽比为2.0
和布局约束,它们的宽度必须在0.0和
100.0之间,而高度必须在0.0和100.0之间。我们将选择宽度100.0(允许的最大值)和高度50.0(以匹配
的宽高比)。

Now consider a second example, this time with an aspect ratio of 2.0 and layout constraints that require the width to be between 0.0 and 100.0 and the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the biggest allowed) and a height of 50.0 (to match the aspect ratio).



//example
new Center(
 child: new AspectRatio(
  aspectRatio: 100 / 100,
  child: new Container(
    decoration: new BoxDecoration(
      shape: BoxShape.rectangle,
      color: Colors.orange,
      )
    ),
  ),
),

也可以使用

  • LayoutBuilder
  • FittedBox
  • CustomMultiChildLayout