如何用Flutter开发Android与iOS英文自定义键盘应用及主题?
用Flutter开发跨平台英文自定义键盘指南
系统级自定义输入法(即能在系统设置中添加的键盘应用)没法完全用Flutter实现,因为需要依赖平台原生的IME框架。通用方案是Flutter负责UI渲染与交互,原生层处理IME核心逻辑,两者通过MethodChannel完成通信。下面是具体实现步骤、可用工具和示例代码:
一、可用工具包
1. flutter_keyboard_ime
这个包封装了Flutter与原生IME交互的基础逻辑,能快速将Flutter视图嵌入系统输入法,省去从零编写原生桥接代码的工作量。
2. 手动封装原生桥接
如果需要更灵活的控制(比如自定义IME的特殊行为),可以自行编写原生IME服务,再嵌入Flutter视图。这种方式自由度更高,但需要具备基础的Android和iOS原生开发能力。
二、实战步骤(以flutter_keyboard_ime为例)
1. 安装依赖
在pubspec.yaml中添加:
dependencies: flutter_keyboard_ime: ^1.0.0 # 替换为最新版本
执行flutter pub get拉取依赖。
2. 原生项目配置
Android端
- 在
AndroidManifest.xml中声明IME服务:
<service android:name=".CustomKeyboardService" android:permission="android.permission.BIND_INPUT_METHOD"> <meta-data android:name="android.view.im" android:resource="@xml/ime_config"/> <intent-filter> <action android:name="android.view.InputMethod"/> </intent-filter> </service>
- 在
res/xml目录下新建ime_config.xml,配置输入法基本信息:
<?xml version="1.0" encoding="utf-8"?> <input-method xmlns:android="http://schemas.android.com/apk/res/android"> <subtype android:label="Custom English Keyboard" android:imeSubtypeMode="keyboard" android:imeSubtypeLocale="en_US"/> </input-method>
- 实现
CustomKeyboardService,将Flutter视图作为输入法UI:
class CustomKeyboardService : InputMethodService() { private lateinit var flutterEngine: FlutterEngine override fun onCreate() { super.onCreate() flutterEngine = FlutterEngine(this) // 配置MethodChannel接收Flutter事件 MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.yourpackage/keyboard_ime").setMethodCallHandler { call, result -> when (call.method) { "sendText" -> { val text = call.argument<String>("text") ?: "" currentInputConnection.commitText(text, 1) result.success(null) } "sendBackspace" -> { currentInputConnection.deleteSurroundingText(1, 0) result.success(null) } else -> result.notImplemented() } } flutterEngine.dartExecutor.executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault() ) } override fun onCreateInputView(): View { return FlutterView(this).apply { attachToFlutterEngine(flutterEngine) } } }
iOS端
- 在
Info.plist中添加输入法扩展配置:
<key>NSExtension</key> <dict> <key>NSExtensionPointIdentifier</key> <string>com.apple.inputmethod.Keyboard</string> <key>NSExtensionPrincipalClass</key> <string>$(PRODUCT_MODULE_NAME).KeyboardExtensionVC</string> </dict>
- 创建
KeyboardExtensionVC,嵌入Flutter视图并配置MethodChannel:
class KeyboardExtensionVC: UIInputViewController { private var flutterView: FlutterView! override func viewDidLoad() { super.viewDidLoad() let engine = FlutterEngine(name: "CustomKeyboardEngine") // 配置MethodChannel接收Flutter事件 MethodChannel(name: "com.yourpackage/keyboard_ime", binaryMessenger: engine.binaryMessenger).setMethodCallHandler { call, result in switch call.method { case "sendText": guard let text = call.arguments as? [String: String], let content = text["text"] else { result.error("Invalid arguments", "Text not found", nil) return } self.textDocumentProxy.insertText(content) result.success(nil) case "sendBackspace": self.textDocumentProxy.deleteBackward() result.success(nil) default: result.notImplemented() } } engine.run() flutterView = FlutterView(frame: view.bounds, engine: engine) view.addSubview(flutterView) // 设置自动布局让Flutter视图占满键盘区域 flutterView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ flutterView.topAnchor.constraint(equalTo: view.topAnchor), flutterView.bottomAnchor.constraint(equalTo: view.bottomAnchor), flutterView.leadingAnchor.constraint(equalTo: view.leadingAnchor), flutterView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } }
3. Flutter端实现键盘UI与主题
以下是支持主题定制的英文键盘组件示例,包含大小写切换、空格和退格功能:
class CustomEnglishKeyboard extends StatefulWidget { final ThemeData? customTheme; final Function(String) onTextInput; final Function() onBackspace; const CustomEnglishKeyboard({ super.key, this.customTheme, required this.onTextInput, required this.onBackspace, }); @override State<CustomEnglishKeyboard> createState() => _CustomEnglishKeyboardState(); } class _CustomEnglishKeyboardState extends State<CustomEnglishKeyboard> { bool _isUpperCase = false; final List<String> _upperKeys = [ 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' ]; final List<String> _lowerKeys = [ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' ]; @override Widget build(BuildContext context) { final theme = widget.customTheme ?? Theme.of(context); return Container( color: theme.colorScheme.background, padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8), child: Column( mainAxisSize: MainAxisSize.min, children: [ _buildKeyRow(_isUpperCase ? _upperKeys.sublist(0,10) : _lowerKeys.sublist(0,10)), const SizedBox(height: 8), _buildKeyRow(_isUpperCase ? _upperKeys.sublist(10,19) : _lowerKeys.sublist(10,19)), const SizedBox(height: 8), Row( children: [ Expanded( flex flex: 2, child: _buildActionButton( onTap: () => setState(() => _isUpperCase = !_isUpperCase), child: Text(_isUpperCase ? 'abc' : 'ABC', style: theme.textTheme.titleLarge), ), ), const SizedBox(width: 8), ..._buildKeyItems(_isUpperCase ? _upperKeys.sublist(19) : _lowerKeys.sublist(19)), const SizedBox(width: 8), Expanded( flex: 2, child: _buildActionButton( onTap: widget.onBackspace, child: Icon(Icons.backspace_outlined, color: theme.colorScheme.onPrimaryContainer), ), ), ], ), const SizedBox(height: 8), _buildActionButton( onTap: () => widget.onTextInput(' '), child: Text('SPACE', style: theme.textTheme.titleLarge?.copyWith(color: theme.colorScheme.onPrimary)), color: theme.colorScheme.primary, ), ], ), ); } Widget _buildKeyRow(List<String> keys) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: _buildKeyItems(keys), ); } List<Widget> _buildKeyItems(List<String> keys) { final theme = widget.customTheme ?? Theme.of(context); return keys.map((key) { return Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 2), child: TextButton( style: TextButton.styleFrom( backgroundColor: theme.colorScheme.surface, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), padding: const EdgeInsets.symmetric(vertical: 16), ), onPressed: () => widget.onTextInput(key), child: Text(key, style: theme.textTheme.titleLarge), ), ), ); }).toList(); } Widget _buildActionButton({required VoidCallback onTap, required Widget child, Color? color}) { final theme = widget.customTheme ?? Theme.of(context); return TextButton( style: TextButton.styleFrom( backgroundColor: color ?? theme.colorScheme.primaryContainer, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), onPressed: onTap, child: child, ); } }
在Flutter入口文件中,通过MethodChannel将输入事件传递给原生:
void main() { runApp(const KeyboardApp()); } class KeyboardApp extends StatelessWidget { const KeyboardApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.blueGrey), useMaterial3: true, ), home: const KeyboardScreen(), ); } } class KeyboardScreen extends StatefulWidget { const KeyboardScreen({super.key}); @override State<KeyboardScreen> createState() => _KeyboardScreenState(); } class _KeyboardScreenState extends State<KeyboardScreen> { static const _imeChannel = MethodChannel('com.yourpackage/keyboard_ime'); void _sendText(String text) async { await _imeChannel.invokeMethod('sendText', {'text': text}); } void _sendBackspace() async { await _imeChannel.invokeMethod('sendBackspace'); } @override Widget build(BuildContext context) { return Scaffold( body: CustomEnglishKeyboard( onTextInput: _sendText, onBackspace: _sendBackspace, // 自定义深色紫色主题示例 customTheme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple, brightness: Brightness.dark), textTheme: const TextTheme( titleLarge: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w500), ), ), ), ); } }
三、主题自定义技巧
- 直接通过
ThemeData的colorScheme、textTheme等属性定义不同风格的主题,比如深色/浅色模式、不同配色方案 - 可提供主题切换选项,用
SharedPreferences保存用户偏好,下次启动键盘时自动加载对应主题
内容的提问来源于stack exchange,提问作者shaun
相关产品推荐
相关产品推荐

