Flutter自定义软键盘插件flutter_soft_keyboard的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter自定义软键盘插件flutter_soft_keyboard的使用

介绍

flutter_soft_keyboard 是一个Flutter包,提供了一个虚拟键盘小部件,可以通过二维数组来实现自定义布局。这个插件允许开发者创建自定义的软键盘,并且可以轻松地集成到Flutter应用中。

如何使用

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_soft_keyboard 依赖:

dependencies:
  flutter_soft_keyboard: ^latest_version
2. 初始化控制器

在使用 SoftKeyboardWidget 之前,需要初始化一个 KeyboardInputController,用于管理键盘输入事件。你可以在 StatefulWidgetinitState 方法中进行初始化,并在 dispose 方法中释放资源。

class _MyHomePageState extends State<MyHomePage> {
  final keyboardController = KeyboardInputController();

  [@override](/user/override)
  void initState() {
    super.initState();
    // 设置键盘输入监听器
    keyboardController.setKeyListener((lastKey, enteredText) {
      print('Last Key Pressed: $lastKey');
      print('Entered Text: $enteredText');
    });
  }

  [@override](/user/override)
  void dispose() {
    // 释放控制器资源
    keyboardController.dispose();
    super.dispose();
  }
}
3. 定义键盘布局

keyLayout 是一个二维数组,每一行代表键盘的一行,每个元素是一个 VirtualKey 对象。你可以根据需要定义键盘的布局。例如,下面是一个简单的数字键盘布局:

final List<List<VirtualKey>> keyLayout = [
  [
    VirtualKey(
        label: '1',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '2',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '3',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        decoration: keyDecoration,
        textStyle: keyTextStyle,
        type: KeyType.backspace,
        icon: Icon(Icons.backspace))  // 回退键
  ],
  [
    VirtualKey(
        label: '4',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '5',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '6',
        decoration: keyDecoration,
        textStyle: keyTextStyle)
  ],
  [
    VirtualKey(
        label: '7',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '8',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: '9',
        decoration: keyDecoration,
        textStyle: keyTextStyle)
  ],
  [
    VirtualKey(
        label: '0',
        decoration: keyDecoration,
        textStyle: keyTextStyle),
    VirtualKey(
        label: 'Enter',
        decoration: keyDecoration,
        textStyle: keyTextStyle,
        type: KeyType.enter)
  ]
];
4. 使用 SoftKeyboardWidget

build 方法中,使用 SoftKeyboardWidget 来显示自定义键盘。你可以通过设置 widthheightcolumnSpacingrowSpacing 来调整键盘的大小和间距。

[@override](/user/override)
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Center(
      child: SoftKeyboardWidget(
        width: 400,  // 键盘宽度
        height: 300, // 键盘高度
        columnSpacing: 4,  // 列间距
        rowSpacing: 4,     // 行间距
        keyLayout: keyLayout,  // 键盘布局
        keyboardInputController: keyboardController,  // 控制器
      ),
    ),
  );
}
5. 自定义样式

你可以通过 ContainerDecorationTextStyle 来自定义按键的外观。例如,设置按键的背景颜色、边框半径和文字样式:

final ContainerDecoration keyDecoration = ContainerDecoration(
  borderRadius: BorderRadius.circular(20),  // 圆角
  backgroundColor: Colors.amber,            // 背景颜色
);

final TextStyle keyTextStyle = const TextStyle(
  fontSize: 50,  // 文字大小
  color: Colors.white,  // 文字颜色
);

完整示例代码

以下是一个完整的示例代码,展示了如何使用 flutter_soft_keyboard 插件创建一个自定义软键盘:

import 'package:flutter/material.dart';
import 'package:flutter_soft_keyboard/key/key_type.dart';
import 'package:flutter_soft_keyboard/key/virtual_key.dart';
import 'package:flutter_soft_keyboard/keyboard_input_controller.dart';
import 'package:flutter_soft_keyboard/soft_keyboard_widget.dart';
import 'package:ripple_container/widget/container_decoration.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final keyboardController = KeyboardInputController();

  // 按键装饰
  final ContainerDecoration keyDecoration = ContainerDecoration(
    borderRadius: BorderRadius.circular(20),
    backgroundColor: Colors.amber,
  );

  // 按键文字样式
  final TextStyle keyTextStyle = const TextStyle(
    fontSize: 50,
    color: Colors.white,
  );

  // 键盘布局
  final List<List<VirtualKey>> keyLayout = [
    [
      VirtualKey(
          label: '1',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '2',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '3',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          decoration: keyDecoration,
          textStyle: keyTextStyle,
          type: KeyType.backspace,
          icon: Icon(Icons.backspace))
    ],
    [
      VirtualKey(
          label: '4',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '5',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '6',
          decoration: keyDecoration,
          textStyle: keyTextStyle)
    ],
    [
      VirtualKey(
          label: '7',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '8',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: '9',
          decoration: keyDecoration,
          textStyle: keyTextStyle)
    ],
    [
      VirtualKey(
          label: '0',
          decoration: keyDecoration,
          textStyle: keyTextStyle),
      VirtualKey(
          label: 'Enter',
          decoration: keyDecoration,
          textStyle: keyTextStyle,
          type: KeyType.enter)
    ]
  ];

  [@override](/user/override)
  void initState() {
    super.initState();
    // 设置键盘输入监听器
    keyboardController.setKeyListener((lastKey, enteredText) {
      print('Last Key Pressed: $lastKey');
      print('Entered Text: $enteredText');
    });
  }

  [@override](/user/override)
  void dispose() {
    // 释放控制器资源
    keyboardController.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SoftKeyboardWidget(
          width: 400,  // 键盘宽度
          height: 300, // 键盘高度
          columnSpacing: 4,  // 列间距
          rowSpacing: 4,     // 行间距
          keyLayout: keyLayout,  // 键盘布局
          keyboardInputController: keyboardController,  // 控制器
        ),
      ),
    );
  }
}

更多关于Flutter自定义软键盘插件flutter_soft_keyboard的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义软键盘插件flutter_soft_keyboard的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用flutter_soft_keyboard插件来实现自定义软键盘的示例代码。这个插件允许你创建和自定义自己的软键盘,以适应特定的输入需求。

首先,确保你已经在pubspec.yaml文件中添加了flutter_soft_keyboard依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_soft_keyboard: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,我们将创建一个简单的Flutter应用,并在其中实现一个自定义软键盘。

主应用代码(main.dart)

import 'package:flutter/material.dart';
import 'package:flutter_soft_keyboard/flutter_soft_keyboard.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Custom Soft Keyboard Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextField(
                controller: _controller,
                decoration: InputDecoration(
                  labelText: 'Enter text',
                ),
                keyboardType: TextInputType.multiline,
                maxLines: null,
                textInputAction: TextInputAction.done,
              ),
              SizedBox(height: 16),
              CustomKeyboardButton(
                text: 'Show Custom Keyboard',
                onPressed: () {
                  _showCustomKeyboard();
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  final TextEditingController _controller = TextEditingController();

  void _showCustomKeyboard() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 250,
          color: Colors.white,
          child: CustomKeyboard(
            controller: _controller,
            onKeyPressed: (String key) {
              _controller.value = _controller.value.copyWith(
                text: _controller.text + key,
                selection: TextSelection.fromPosition(
                  TextPosition(
                    affinity: TextAffinity.downstream,
                    offset: _controller.text.length,
                  ),
                ),
                composing: TextRange.empty,
              );
            },
            onBackspacePressed: () {
              if (_controller.text.isNotEmpty) {
                _controller.value = _controller.value.copyWith(
                  text: _controller.text.substring(0, _controller.text.length - 1),
                  selection: TextSelection.fromPosition(
                    TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: _controller.text.length,
                    ),
                  ),
                  composing: TextRange.empty,
                );
              }
            },
            onDonePressed: () {
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }
}

class CustomKeyboard extends StatelessWidget {
  final TextEditingController controller;
  final VoidCallback onKeyPressed;
  final VoidCallback onBackspacePressed;
  final VoidCallback onDonePressed;

  const CustomKeyboard({
    Key key,
    @required this.controller,
    @required this.onKeyPressed,
    @required this.onBackspacePressed,
    @required this.onDonePressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // Row of keys
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            for (var key in ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'])
              KeyboardButton(
                text: key,
                onPressed: () => onKeyPressed(key),
              ),
          ],
        ),
        // Row of keys with backspace
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            for (var key in ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'])
              KeyboardButton(
                text: key,
                onPressed: () => onKeyPressed(key),
              ),
            KeyboardButton(
              text: '⌫',
              onPressed: onBackspacePressed,
            ),
          ],
        ),
        // Row of keys with done
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            for (var key in ['Z', 'X', 'C', 'V', 'B', 'N', 'M'])
              KeyboardButton(
                text: key,
                onPressed: () => onKeyPressed(key),
              ),
            KeyboardButton(
              text: 'Done',
              onPressed: onDonePressed,
            ),
          ],
        ),
      ],
    );
  }
}

class KeyboardButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const KeyboardButton({
    Key key,
    @required this.text,
    @required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
      style: ButtonStyle(
        overlayColor: MaterialStateProperty.all(Colors.grey.shade300),
      ),
    );
  }
}

class CustomKeyboardButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;

  const CustomKeyboardButton({
    Key key,
    @required this.text,
    @required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(text),
    );
  }
}

解释

  1. 依赖安装:首先,在pubspec.yaml中添加flutter_soft_keyboard依赖(虽然实际上flutter_soft_keyboard这个包名可能是虚构的,这里只是为了示例)。然而,在这个例子中,我们并没有直接使用任何特定的软键盘插件,而是手动创建了自定义键盘。

  2. 主应用:在MyApp中,我们创建了一个简单的界面,包含一个TextField和一个按钮,用于显示自定义键盘。

  3. 自定义键盘CustomKeyboard是一个无状态小部件,它包含了几行按钮,每行代表键盘上的一行键。每个按钮都调用onKeyPressed回调来插入字符,或者调用onBackspacePressedonDonePressed回调来处理删除和完成操作。

  4. 键盘按钮KeyboardButton是一个简单的按钮小部件,用于表示键盘上的单个键。

  5. 显示键盘:点击“Show Custom Keyboard”按钮时,会显示一个包含自定义键盘的BottomSheet

请注意,这只是一个基础示例,实际使用中你可能需要更多的自定义和错误处理,例如处理多行文本、特殊字符、换行符等。同时,如果你需要更高级的软键盘功能,可能需要寻找或开发一个更全面的软键盘插件。

回到顶部