TSR*_*TSR 2 responsive-design flutter flutter-layout
如果设备的屏幕宽度超过某个阈值,如何将“列”窗口小部件动态更改为“行”窗口小部件?
用例是当用户在平板电脑或横向模式下使用该应用程序时,布局应有所不同,以优化可用宽度的使用。
在CSS flexbox中,就像将类从flex-row更改为flex-column一样简单,但是在Flutter中,使用了小部件。
要根据设备方向进行更改,您可以执行以下操作:
Orientation orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? Column(children: <Widget>[])
: Row(children: <Widget>[]);
Run Code Online (Sandbox Code Playgroud)
我写了一个助手来执行此操作(列到行)。
import 'package:flutter/material.dart';
class OrientationSwitcher extends StatelessWidget {
final List<Widget> children;
const OrientationSwitcher({Key key, this.children}) : super(key: key);
@override
Widget build(BuildContext context) {
Orientation orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? Column(children: children)
: Row(children: children);
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它...
Widget build(BuildContext context) {
return OrientationSwitcher(
children: <Widget>[
// place children here like its a column or row.
]
)
}
Run Code Online (Sandbox Code Playgroud)
您还可以使用 Flex() 或任何其他小部件来执行此操作。
此外,除了方向之外,还有更多选项可用,请务必查看 Flutter 文档上的 MediaQuery.of(context) 实现。
Row并Column共享称为Flex轴方向的公共父级。只需更改的值,direction就可以将a更改Flex为行或列。
要获取屏幕宽度,可以使用MediaQuery.of(context).size.width。
您的小部件应如下所示:
@override
Widget build(BuildContext context) {
bool isScreenWide = MediaQuery.of(context).size.width >= kMinWidthOfLargeScreen;
return Scaffold(
body: Flex(
direction: isScreenWide ? Axis.horizontal : Axis.vertical,
children: <Widget>[
...
],
)
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
360 次 |
| 最近记录: |