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

相关文章

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Linux创建服务使用systemctl管理详解

《Linux创建服务使用systemctl管理详解》文章指导在Linux中创建systemd服务,设置文件权限为所有者读写、其他只读,重新加载配置,启动服务并检查状态,确保服务正常运行,关键步骤包括权... 目录创建服务 /usr/lib/systemd/system/设置服务文件权限:所有者读写js,其他

idea+spring boot创建项目的搭建全过程

《idea+springboot创建项目的搭建全过程》SpringBoot是Spring社区发布的一个开源项目,旨在帮助开发者快速并且更简单的构建项目,:本文主要介绍idea+springb... 目录一.idea四种搭建方式1.Javaidea命名规范2JavaWebTomcat的安装一.明确tomcat

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

Git打标签从本地创建到远端推送的详细流程

《Git打标签从本地创建到远端推送的详细流程》在软件开发中,Git标签(Tag)是为发布版本、标记里程碑量身定制的“快照锚点”,它能永久记录项目历史中的关键节点,然而,仅创建本地标签往往不够,如何将其... 目录一、标签的两种“形态”二、本地创建与查看1. 打附注标http://www.chinasem.cn

SpringBoot AspectJ切面配合自定义注解实现权限校验的示例详解

《SpringBootAspectJ切面配合自定义注解实现权限校验的示例详解》本文章介绍了如何通过创建自定义的权限校验注解,配合AspectJ切面拦截注解实现权限校验,本文结合实例代码给大家介绍的非... 目录1. 创建权限校验注解2. 创建ASPectJ切面拦截注解校验权限3. 用法示例A. 参考文章本文

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息