Flutter创建自定义的软键盘

2024-04-30 16:20

本文主要是介绍Flutter创建自定义的软键盘,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考代码:

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();},),],),);}
}

这篇关于Flutter创建自定义的软键盘的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/949338

相关文章

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

python如何创建等差数列

《python如何创建等差数列》:本文主要介绍python如何创建等差数列的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python创建等差数列例题运行代码回车输出结果总结python创建等差数列import numpy as np x=int(in

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam

怎么用idea创建一个SpringBoot项目

《怎么用idea创建一个SpringBoot项目》本文介绍了在IDEA中创建SpringBoot项目的步骤,包括环境准备(JDK1.8+、Maven3.2.5+)、使用SpringInitializr... 目录如何在idea中创建一个SpringBoot项目环境准备1.1打开IDEA,点击New新建一个项