首页 > 其他分享 >flutter 效果实现 —— 键盘快捷键绑定

flutter 效果实现 —— 键盘快捷键绑定

时间:2022-09-21 00:44:24浏览次数:83  
标签:const class 绑定 快捷键 controller extends context override flutter

效果:

代码:

class ShortcutPage extends StatefulWidget {
  ShortcutPage({super.key});

  @override
  State<ShortcutPage> createState() => _ShortcutPageState();
}

class _ShortcutPageState extends State<ShortcutPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Shortcuts.manager(
        // return Shortcuts(
        //   shortcuts: <LogicalKeySet, Intent>{
        //     LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyA): const SelectAllIntent(),
        //   },
        manager: LoggingShortcutManager(
            // ① 快捷方式与 Intent 的映射
            shortcuts: <LogicalKeySet, Intent>{
              LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyU): const ClearIntent(),
            }),
        child: Column(
          children: [
            Expanded(child: ClearTextField(title: "Shortcuts and Actions Demo")),
            Expanded(child: TextSelectionField()),
          ],
        ),
      ),
    );
  }
}

/// 文本清除组件
class ClearTextField extends StatefulWidget {
  const ClearTextField({super.key, required this.title});

  final String title;

  @override
  State<ClearTextField> createState() => _ClearTextFieldState();
}

class _ClearTextFieldState extends State<ClearTextField> {
  late TextEditingController controller = TextEditingController();

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Actions(
      dispatcher: LoggingActionDispatcher(),
      //② Intent 与 Action 的映射
      actions: <Type, Action<Intent>>{
        ClearIntent: ClearAction(controller),
      },
      child: Builder(builder: (context) {
        return Row(
          children: <Widget>[
            const Spacer(),
            Expanded(
              child: TextField(controller: controller),
            ),
            IconButton(
              icon: const Icon(Icons.clear),
              onPressed: Actions.handler<ClearIntent>(context, const ClearIntent()),
            ),
            const Spacer(),
          ],
        );
      }),
    );
  }
}

//③ 一个Intent 子类,用于联系 Shortcut 与 Action
class ClearIntent extends Intent {
  const ClearIntent();
}

//④ Action 快捷键按下后所执行的操作
class ClearAction extends Action<ClearIntent> {
  ClearAction(this.controller);

  final TextEditingController controller;

  @override
  Object? invoke(covariant ClearIntent intent) {
controller.clear();
    return null;
  }
}

/// Action分发日志
class LoggingActionDispatcher extends ActionDispatcher {
  @override
  Object? invokeAction(
    covariant Action<Intent> action,
    covariant Intent intent, [
    BuildContext? context,
  ]) {
    print('Action invoked: $action($intent) from $context');
    super.invokeAction(action, intent, context);

    return null;
  }
}

/// 快捷方式管理(添加日志)
class LoggingShortcutManager extends ShortcutManager {
  LoggingShortcutManager({super.shortcuts});

  @override
  KeyEventResult handleKeypress(BuildContext context, RawKeyEvent event) {
    final KeyEventResult result = super.handleKeypress(context, event);
    if (result == KeyEventResult.handled) {
      print('Handled shortcut $event in $context');
    }
    return result;
  }
}


/// 文本全选组件
class TextSelectionField extends StatefulWidget {
  const TextSelectionField({Key? key}) : super(key: key);

  @override
  State<TextSelectionField> createState() => _TextSelectionFieldState();
}

class _TextSelectionFieldState extends State<TextSelectionField> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onDoubleTap: () {
        _controller.selection = TextSelection(baseOffset: 0, extentOffset: _controller.value.text.length);
      },
      child: Row(
        children: <Widget>[
          const Spacer(),
          Expanded(
            child: TextField(controller: _controller, focusNode: _focusNode,),
          ),
          IconButton(
              icon: const Icon(Icons.select_all),
              onPressed: () {
                //按下按钮时,焦点转移到按钮自身,因此这里需要手动将焦点移动到原来的输入框
                _focusNode.requestFocus();
                // _controller.selection = TextSelection(baseOffset: 0, extentOffset: _controller.value.text.length);
                _controller.selection = _controller.selection.copyWith(
                  baseOffset: 0,
                  extentOffset: _controller.text.length,
                  affinity: _controller.selection.affinity,
                );
              }
          ),
          const Spacer(),
        ],
      ),
    );
  }
}

标签:const,class,绑定,快捷键,controller,extends,context,override,flutter
From: https://www.cnblogs.com/lemos/p/16714222.html

相关文章

  • jquery动态为select 绑定数据
      functiongetChapters(courseid){$.ajax({url:'/chapter/getChapersByUidCourseID?courseID='+courseid,su......
  • 分析mybatis的#{}、${}(#绑定变量超过一定值导致Oracle挂掉)
    我后来改成了1万条,数据库相对小点压力不大,也不会出现重启的问题; 最近跟数据库干上了先说下问题起源,算奖确认订单,需要批量update订单,查了相关资料,是mybatis一次性绑定变......
  • MAUI学习笔记(三)-视图绑定模型
    一、创建实体模型-About.csusingSystem;namespaceTest.Models{///<summary>///关于页///</summary>publicclassAbout{///<......
  • 使用AJAX绑定点击事件将接口值返回渲染到指定位置
    AJAX是局部的刷新或者叫做无刷新技术首先是js部分,这里注意不紧要引入express模块,还需要把cors模块也引入在下面添加了判断,用来判断所取得的随机值是否在0.5以上  ......
  • Flutter耳返和双声道功能的实现
    1耳返功能简介ZEGOExpressSDK提供了Flutter耳返和双声道的功能,在视频直播、K歌、音频录制等场景下广泛应用,开发者可根据实际业务场景需要设置,一套代码可实现跨平台音......
  • Vue的双向绑定原理
    只是储备:什么是MVVM模式,和MVC的区别?MVVM是模型-视图-视图模型,Vue和React都在使用MVVM模式,vm是v和m的桥梁,view页面和m模型数据之间通过vm是存在双向联系的; vue实现双向数......
  • 常用快捷键、命令
    快捷指令ctrl+c:复制ctrl+v:粘贴ctrl+a:全选ctrl+x:剪切ctrl+z:撤销ctrl+s:保存alt+F4:关闭窗口 打开cmd的方式开始+Windows系统+找到命令提示符win键+R......
  • 快捷键
    ctrl+c:复制ctrl+v:粘贴ctrl+a:全选ctrl+x:剪贴ctrl+z:撤回ctrl+s:保存window+r:运行window+e+:我的电脑ctrl+shift+nsc:任务管理器dom快捷键 /这个后面加参数\这个......
  • vscode 切换项目快捷键 Alt + Shift + P 插件 Project Manager
    vscode切换项目快捷键Alt+Shift+P插件ProjectManager需求快速切换同时打开的项目解决方案Alt+Shift+P话说这个插件很早就用了,但是由于每次需要左......
  • Java学习第二天-快捷键
    快捷键Ctrl+CCtrl+VCtrl+ACtrl+XCtrl+ZCtrl+SAlt+F4Shift+Deleteexplorer打开CMD的方式开始+系统+命令提示符Win键+R,输入cmd打开命令提示符(推荐)任意文......