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

Flutter应用全屏模式切换需求:支持F11/ESC退出全屏

解决方案

要实现F11切换全屏、ESC退出全屏的功能,你需要结合window_manager包的全屏控制API,加上Flutter的键盘事件监听来捕获按键操作。以下是具体实现步骤:

1. 确认依赖window_manager

如果还没添加,先在pubspec.yaml中加入依赖:

dependencies:
  window_manager: ^0.3.8 # 可替换为最新版本

2. 完整代码实现

替换原有的main函数,并在根Widget中添加键盘事件监听:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await windowManager.ensureInitialized();

  // 启动时默认进入全屏
  await windowManager.setFullScreen(true);
  await windowManager.show();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 处理键盘按键事件
  void _handleKeyPress(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      final key = event.logicalKey;
      // F11切换全屏状态
      if (key == LogicalKeyboardKey.f11) {
        _toggleFullScreen();
      }
      // ESC直接退出全屏
      else if (key == LogicalKeyboardKey.escape) {
        _exitFullScreen();
      }
    }
  }

  // 切换全屏状态
  Future<void> _toggleFullScreen() async {
    final currentState = await windowManager.isFullScreen();
    await windowManager.setFullScreen(!currentState);
  }

  // 退出全屏
  Future<void> _exitFullScreen() async {
    await windowManager.setFullScreen(false);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: RawKeyboardListener(
          focusNode: FocusNode(),
          autofocus: true,
          onKey: _handleKeyPress,
          child: const Center(
            child: Text(
              "按F11切换全屏,ESC退出全屏",
              style: TextStyle(fontSize: 18),
            ),
          ),
        ),
      ),
    );
  }
}

关键说明

  • 键盘事件捕获:通过RawKeyboardListener实现全局按键监听,autofocus: true确保根Widget能获取焦点,捕获所有按键操作。
  • 全屏状态控制:
    • _toggleFullScreen:先通过windowManager.isFullScreen()获取当前状态,再反向设置全屏状态,实现F11切换功能。
    • _exitFullScreen:直接将全屏状态设为false,满足ESC一键退出的需求。

内容的提问来源于stack exchange,提问作者Joan Manuel De La Cruz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:02:38