正文:
使用 Flutter
,我们可以使用 MediaQuery
和 LayoutBuilders
来创建适用于手机和平板电脑的布局。这些工具可以帮助我们根据设备的屏幕尺寸和方向来调整布局。通过使用 MediaQuery
,我们可以获取设备的屏幕尺寸和方向信息,并根据这些信息来调整布局的大小和位置。而 LayoutBuilders
则可以帮助我们根据不同的约束条件来构建不同的布局。这些工具的结合使用,可以让我们的应用在不同的设备上都能够呈现出最佳的布局效果。
首先,我们需要创建一个函数来返回两个 GridView
。
// https
://www
.huizhanii
.com
gridviewForPhone
() {
return
Padding
(
padding
: EdgeInsets
.all
(5.0),
child
: GridView
.count
(
crossAxisCount
: 2,
childAspectRatio
: 1.0,
mainAxisSpacing
: 4.0,
crossAxisSpacing
: 4.0,
children
: List
.generate
(100, (index
) {
return
Card
(
child
: Container
(
alignment
: Alignment
.center
,
color
: Colors
.red
[100 * (index
% 9)],
child
: Text
('$index
'),
),
);
}),
),
);
}
gridviewForTablet
() {
return
Padding
(
padding
: EdgeInsets
.all
(5.0),
child
: GridView
.count
(
crossAxisCount
: 4,
childAspectRatio
: 1.0,
mainAxisSpacing
: 4.0,
crossAxisSpacing
: 4.0,
children
: List
.generate
(100, (index
) {
return
Card
(
child
: Container
(
alignment
: Alignment
.center
,
color
: Colors
.green
[100 * (index
% 9)],
child
: Text
('$index
'),
),
);
}),
),
);
}
在这个函数中,Phone
GridView
将每行显示 2 个单元格,而平板电脑将每行显示 4 个。
使用 MediaQuery
为了确定布局,我们将使用 MediaQuery
。为此,我们将声明三个变量。
我们假设 600.0 作为平板电脑的边界。
现在我们的构建方法将更改为
现在我们将方法更改为
// https
://www
.huizhanii
.com
gridviewForPhone
(Orientation
orientation
) {
...
GridView
.count
(
crossAxisCount
: orientation
.portrait
? 2 : 4
...
}
gridviewForTablet
(Orientation
orientation
) {
...
GridView
.count
(
crossAxisCount
: orientation
.portrait
? 4 : 6
}
使用 LayoutBuilder
这是进行比较的示例
为了简单起见,我们只是使用构建器约束检查设备的最大宽度。
因此,一旦您的设备超过 600.0 的最大宽度,可能在横向模式下它最终会显示平板电脑的 GridView
。
转载请注明:汇站网 » 如何在 Flutter
中创建手机/平板电脑布局(MediaQuery
和 LayoutBuilders
)教程