根據方向更新 UI
在某些情況下,您希望在使用者將螢幕從直向模式旋轉到橫向模式時更新應用程式的顯示。例如,應用程式可能會在直向模式中一個接著一個顯示項目,但在橫向模式中將相同的項目並排顯示。
在 Flutter 中,您可以根據給定的 Orientation
建立不同的佈局。在此範例中,使用以下步驟建立一個在直向模式下顯示兩欄,在橫向模式下顯示三欄的列表
- 建立一個具有兩欄的
GridView
。 - 使用
OrientationBuilder
來更改欄數。
1. 建立一個具有兩欄的 GridView
#首先,建立一個要使用的項目列表。不要使用普通的列表,而是建立一個以網格顯示項目的列表。現在,建立一個具有兩欄的網格。
return GridView.count(
// A list with 2 columns
crossAxisCount: 2,
// ...
);
若要深入了解如何使用 GridViews
,請參閱建立網格列表的食譜。
2. 使用 OrientationBuilder
來更改欄數
#若要判斷應用程式目前的 Orientation
,請使用 OrientationBuilder
小工具。OrientationBuilder
會藉由比較父小工具可用的寬度和高度來計算目前的 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,
),
);
}),
);
},
),
);
}
}
鎖定裝置方向
#在上一節中,您學習了如何調整應用程式 UI 以適應裝置方向的變更。
Flutter 也允許您使用 DeviceOrientation
的值來指定您的應用程式支援的方向。您可以選擇
- 將應用程式鎖定為單一方向,例如僅限
portraitUp
位置,或... - 允許使用多個方向,例如
portraitUp
和portraitDown
,但不允許橫向。
在應用程式的 main()
方法中,使用您的應用程式支援的偏好方向列表呼叫 SystemChrome.setPreferredOrientations()
。
若要將裝置鎖定為單一方向,您可以傳遞包含單一項目的列表。
如需所有可能值的列表,請查看 DeviceOrientation
。
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(const MyApp());
}
除非另有說明,否則本網站上的文件反映了 Flutter 的最新穩定版本。本頁面最後更新於 2024-06-26。 檢視原始碼 或 回報問題。