根據螢幕方向更新介面
一般情況下,一旦一個應用的螢幕方向發生了改變,比如從橫屏變成豎屏,其設計也將跟著更新。例如,在縱向模式下,我們可能想要依次顯示各個專案,但在橫向模式下,我們會把這些相同的專案並排放置。
在 Flutter 中,我們可以根據給定的 Orientation
建立不同的佈局。本範例中,我們將建立一個清單,在縱向模式下顯示兩列,在橫向模式下顯示三列。
-
建立一個列的數量為 2 的
GridView
; -
使用
OrientationBuilder
更改列數。
GridView
1. 建立一個列的數量為 2 的 首先,我們需要一個專案的清單來配合完成。我們需要使用一個在網格中顯示專案的清單而非一個普通的清單。現在,我們將建立一個包含兩個列的網格。
return GridView.count(
// A list with 2 columns
crossAxisCount: 2,
// ...
);
要了解有關使用 GridViews
的更多訊息,請參閱這個教程文件:建立一個網格清單。
OrientationBuilder
更改列數。
2. 使用 為了確定當前的螢幕方向 Orientation
,我們可以使用 OrientationBuilder
widget。
OrientationBuilder
透過比較父 widget 的可用寬度和高度來計算當前的 Orientation
,並在父視窗大小更改時重建。
使用 Orientation
,我們可以建立一個清單,在縱向模式下顯示兩列,在橫向模式下顯示三列。
body: OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
// Create a grid with 2 columns in portrait mode,
// or 3 columns in landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
);
},
),
互動式範例
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Orientation Demo';
return const MaterialApp(
title: appTitle,
home: OrientationList(
title: appTitle,
),
);
}
}
class OrientationList extends StatelessWidget {
final String title;
const OrientationList({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
// Create a grid with 2 columns in portrait mode, or 3 columns in
// landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
// Generate 100 widgets that display their index in the List.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.displayLarge,
),
);
}),
);
},
),
);
}
}
Locking device orientation
In the previous section, you learned how to adapt the app UI to device orientation changes.
Flutter also allows you to specify the orientations your app supports
using the values of DeviceOrientation
. You can either:
- Lock the app to a single orientation, like only the
portraitUp
position, or… - Allow multiple orientations, like both
portraitUp
andportraitDown
, but not landscape.
In the application main()
method,
call SystemChrome.setPreferredOrientations()
with the list of preferred orientations that your app supports.
To lock the device to a single orientation, you can pass a list with a single item.
For a list of all the possible values, check out DeviceOrientation
.
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(const MyApp());
}