Flutter创建自定义的软键盘

ops/2024/9/23 11:17:20/

参考代码:

Flutter - Create Custom Keyboard Examples

本文贴出的代码实现了一个输入十六进制数据的键盘:

(1)支持长按退格键连续删除字符;

(2)可通过退格键删除选中的文字;

(3)监听文本变化(包括粘贴剪切导致的变化)。 

hex_keyboard.dart

import 'dart:async';import 'package:flutter/material.dart';class HexKeyboard extends StatefulWidget {final TextEditingController controller;final void Function() onDone;final void Function(String) onTextChanged;const HexKeyboard({super.key,required this.controller,required this.onDone,required this.onTextChanged,});@overrideState<HexKeyboard> createState() => _HexKeyboardState();
}class _HexKeyboardState extends State<HexKeyboard> {late TextEditingController _controller;final Widget _horizontalPadding = const SizedBox(width: 1.0);final Widget _verticalPadding = const SizedBox(height: 1.0);Timer? _timer;@overridevoid initState() {super.initState();_controller = widget.controller;}void _handleType(String text) {int position = _controller.selection.base.offset;var value = _controller.text;if (value.isEmpty) {_controller.text = text;} else {_controller.text = value.substring(0, position) +text +value.substring(position, value.length);}_controller.selection =TextSelection.fromPosition(TextPosition(offset: position + 1));widget.onTextChanged(_controller.text);}void _handleBackspace() {final value = _controller.text;if (value.isNotEmpty) {final start = _controller.selection.start;final end = _controller.selection.end;print("selection.start=$start, selection.end=$end");final int offset;if(end > 0) {if(start == end) {_controller.text = value.substring(0, start - 1) +value.substring(start, value.length);offset = start - 1;} else {_controller.text = value.substring(0, start) +value.substring(end, value.length);offset = start;}_controller.selection =TextSelection.fromPosition(TextPosition(offset: offset));widget.onTextChanged(_controller.text);}}}Widget _buildButton(String text,{VoidCallback? onPressed,VoidCallback? onLongPressStart,VoidCallback? onLongPressUp}) {return Expanded(child: Container(color: Colors.white,child: GestureDetector(onLongPressStart: (e) {onLongPressStart?.call();},onLongPressUp: onLongPressUp,child: TextButton(onPressed: onPressed ?? () => _handleType(text),child: Text(text,style: const TextStyle(color: Colors.black, fontSize: 16),),),),),);}@overrideWidget build(BuildContext context) {return _buildButtonKeyboard();}Widget _buildButtonRow(String key1, String key2, String key3) {return Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: [_horizontalPadding,_buildButton(key1),_horizontalPadding,_buildButton(key2),_horizontalPadding,_buildButton(key3),_horizontalPadding,],);}Widget _buildButtonKeyboard() {return Container(color: const Color(0xffdddddd),child: Column(children: [_verticalPadding,_buildButtonRow('A', 'B', 'C'),_verticalPadding,_buildButtonRow('D', 'E', 'F'),_verticalPadding,_buildButtonRow('1', '2', '3'),_verticalPadding,_buildButtonRow('4', '5', '6'),_verticalPadding,_buildButtonRow('7', '8', '9'),_verticalPadding,Row(children: [_horizontalPadding,_buildButton('⌫',onPressed: _handleBackspace,onLongPressStart: () {_timer =Timer.periodic(const Duration(milliseconds: 50), (timer) {_handleBackspace();});},onLongPressUp: () {_timer?.cancel();},),_horizontalPadding,_buildButton('0'),_horizontalPadding,_buildButton('Done',onPressed: widget.onDone,),_horizontalPadding,],),_verticalPadding,],),);}
}

 hex_input_screen.dart

import 'package:flutter/material.dart';class HexInputScreen extends StatefulWidget {final String text;const HexInputScreen({super.key, required this.text});@overrideState<HexInputScreen> createState() => _HexInputScreenState();
}class _HexInputScreenState extends State<HexInputScreen> {late TextEditingController _controller;final FocusNode _focus = FocusNode();late ValueNotifier<bool> _focusValueNotifier;int _byteCount = 0;int _toByteCount(String hex) {return hex.length % 2 == 0 ? hex.length ~/ 2 : hex.length ~/ 2 + 1;}void _onTextChanged(String text) {//更新字节数setState(() {_byteCount = _toByteCount(text);});}@overridevoid initState() {_controller = TextEditingController(text: widget.text);_focus.addListener(_handleFocusChange);_focusValueNotifier = ValueNotifier<bool>(_focus.hasFocus);_focus.requestFocus();setState(() {_byteCount = widget.text.length;});super.initState();}@overridevoid dispose() {super.dispose();_focus.removeListener(_handleFocusChange);_focus.dispose();}void _handleFocusChange() {_focusValueNotifier.value = _focus.hasFocus;}void _onDone() {print(_controller.text);Navigator.pop(context, _controller.text);}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text('HEX' /*, style: TextStyle(color: Colors.white)*/),// backgroundColor: Colors.black,),body: Column(mainAxisAlignment: MainAxisAlignment.start,children: [const SizedBox(height: 10),Text('已输入 $_byteCount 字节'),Padding(padding: const EdgeInsets.all(8.0),child: TextField(decoration: const InputDecoration(border: OutlineInputBorder(borderSide: BorderSide(color: Colors.grey,width: 1,),),),controller: _controller,keyboardType: TextInputType.none,focusNode: _focus,maxLines: 12,maxLength: 1024,onChanged: _onTextChanged,//这里监听粘贴剪切导致的变化),),const Spacer(),ListenableBuilder(listenable: _focusValueNotifier,builder: (BuildContext context, Widget? child) {return _focus.hasFocus? HexKeyboard(controller: _controller,onDone: _onDone,onTextChanged: _onTextChanged,//这里监听自定义键盘导致的变化): Container();},),],),);}
}


http://www.ppmy.cn/ops/24860.html

相关文章

Agent AI智能体的未来

随着科技的飞速发展&#xff0c;Agent AI智能体的智能化水平也在不断提高&#xff0c;它们将在未来社会中扮演更加重要的角色。以下是我对Agent AI智能体未来发展趋势的探讨&#xff0c;涵盖技术进步与创新、伦理与法律规范以及经济与就业市场三个方面。 一、技术进步与创新 …

【JDBC】数据库连接池

1 简介 1.1 概念 持有多个数据库连接的容器&#xff0c;当程序需要操作数据库的时候&#xff0c;直接可以从池中取出连接&#xff0c;使用完成之后&#xff0c;再放回到池中。 1.2 优点 节省资源。如果每次访问数据库&#xff0c;都需要创建新的连接&#xff0c;在使用完成后…

Oracle 表分区

1.概述 分区表就是将表在物理存储层面分成多个小的片段&#xff0c;这些片段即称为分区&#xff0c;每个分区保存表的一部分数据&#xff0c;表的分区对上层应用是完全透明的&#xff0c;从应用的角度来看&#xff0c;表在逻辑上依然是一个整体。 目的&#xff1a;提高大表的查…

常见设计模式及其Rust实现

本文提供了一个设计模式的综合概述&#xff0c;涵盖了设计模式的必要性&#xff0c;基本原则以及23种常见模式的概括性描述。结合Rust语言自身的特性&#xff0c;重点阐述了Rust中Builder&#xff0c;Combinator&#xff0c;RAII,Typestate(state machine), Command, Strategy和…

Go语言基本语法(四)函数与变量的作用域

函数 Go语言中的函数&#xff08;Function&#xff09;是执行特定任务的代码块&#xff0c;它们是构建程序的基本单位之一。函数可以接受输入参数&#xff0c;执行一系列操作&#xff0c;并可返回结果。Go语言的函数设计简洁&#xff0c;强调代码的清晰度和模块化。下面是Go函…

内存溢出如何实现自动化重启

linux内存溢出系统自动化重启 为了在Linux系统中自动化处理内存溢出&#xff08;Out of Memory, OOM&#xff09;情况并重启系统&#xff0c;你可以使用以下步骤和脚本&#xff1a; 使用cron守护进程来定期检查内存使用情况。 如果内存使用量超过某个阈值&#xff0c;触发系统…

初步认识Vscode

4.26初步认识Vscode &#xff08;一&#xff09;快捷键的使用 1. 打开控制端 ctrl ~2. 结束终端 ctrl c3. 多行同时对齐输出 按住shift alt 光标多选4. 多行同时任意位置输出 按住alt 光标单点你想要输入的位置5. 代码太长了&#xff0c;想混行编辑 alt z6. 打开设置控制…

FPGA之zynq_DDR(1)

学习一下关于DDR的知识和vivado操作吧。 用PS控制DDR内存读写 【ZYNQ-7000开发之六】使用PS控制DDR3的读写_xil_in32读取ddr数据-CSDN博客 在新建block design时&#xff0c;选择DDR&#xff0c;选择UART&#xff08;为什么要用uart&#xff1f;&#xff09; 找到DDR的地址&a…