You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中根据屏幕尺寸条件锁定设备方向

解决方案

你可以通过MediaQuery获取屏幕尺寸,结合设定的阈值判断并自动锁定对应方向,同时监听屏幕尺寸变化以动态更新锁定规则。以下是完整实现:

完整代码实现

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// 定义尺寸阈值
const double thresholdWidth = 430;
const double thresholdHeight = 932;

// 锁定竖屏
Future<void> lockPortrait() async {
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

// 锁定横屏
Future<void> lockLandscape() async {
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);
}

// 根据屏幕尺寸自动锁定方向
Future<void> lockOrientationByScreenSize(BuildContext context) async {
  final screenSize = MediaQuery.of(context).size;
  // 按需求判断:屏幕宽高均小于等于阈值时锁定竖屏,否则锁定横屏
  if (screenSize.width <= thresholdWidth && screenSize.height <= thresholdHeight) {
    await lockPortrait();
  } else {
    await lockLandscape();
  }
}

// 示例Widget:集成方向锁定逻辑
class AutoOrientationLockPage extends StatefulWidget {
  const AutoOrientationLockPage({super.key});

  @override
  State<AutoOrientationLockPage> createState() => _AutoOrientationLockPageState();
}

class _AutoOrientationLockPageState extends State<AutoOrientationLockPage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 页面初始化时锁定方向
    _updateOrientation();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // 屏幕尺寸变化(旋转、分屏等)时更新锁定方向
    _updateOrientation();
  }

  Future<void> _updateOrientation() async {
    await lockOrientationByScreenSize(context);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(child: Text('根据屏幕尺寸自动锁定方向')),
    );
  }
}

关键说明

  • 通过MediaQuery.of(context).size获取当前屏幕的实际宽高。
  • 封装独立的竖屏/横屏锁定方法,逻辑拆分更清晰。
  • 使用WidgetsBindingObserver监听屏幕尺寸变化,确保在屏幕旋转、分屏等场景下,方向锁定能自动更新。
  • 在页面初始化和尺寸变化时,调用统一的方向判断方法完成锁定。

内容的提问来源于stack exchange,提问作者Jhonatta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 01:45:06