Flutter自定义键盘插件fulde_keyboard的使用

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

Flutter自定义键盘插件fulde_keyboard的使用

关于

fulde_keyboard 是一个用于在设备(如自动柜员机和自助服务终端)上显示虚拟键盘的简单包。该库用Dart编写,并且没有任何本地代码依赖。

这个项目是从 virtual_keyboard 项目分叉出来的,因为 virtual_keyboard 项目仅用于在屏幕上显示单语言按钮。然而,这个项目将处理事件并支持多语言。

特性及待办事项列表

  • 已完成 多语言支持。
  • 已完成 可自定义布局。
  • 已完成 可选择弹出浮动键盘/数字键盘。
  • 已完成 添加长按空格键弹出窗口以选择另一个键盘。
  • 待办 添加阿拉伯语和豪萨语键盘(Rabi’at字体)。
  • 待办 优化。
  • 待办 添加输入结果查看器并处理事件。
  • 待办 添加拼写检查器。

截图

截图

截图


参考

FuldeKeyboard

Flutter组件,用于显示虚拟键盘。

// 键盘类型:可以是数字或字母数字。
FuldeKeyboardType type
// 按键事件回调。按下时调用带有按下的`Key`对象。
Function onKeyPress;
// 虚拟键盘高度。默认为300。
double height;
/// 虚拟键盘宽度。默认为全屏宽度。
double width;
// 键文字和图标的颜色。
Color textColor;
// 键文字的字体大小。
double fontSize;
// 仅启用大写字母。
bool alwaysCaps;
/// 多语言或多语言单一布局自定义。
FuldeKeyboardLayoutKeys customLayoutKeys;
/// 用于多语言的默认布局,默认仅支持英语。
/// 如果customLayoutKeys不为空,则会被忽略。
List<FuldeKeyboardDefaultLayouts> defaultLayouts;
/// 布局反转以解决右到左语言问题,默认为false。
bool reverseLayout;

FuldeKeyboardType

虚拟键盘类型的枚举。

// 仅数字。
FuldeKeyboardType.Numeric
// 字母数字:字母`[A-Z]` + 数字`[0-9]` + `@` + `.`。
FuldeKeyboardType.Alphanumeric

FuldeKeyboardKey

虚拟键盘键。

// 键的文字。
String text
// 键的大写文字。
String capsText;
// 动作或字符串。
FuldeKeyboardKeyType keyType;
// 键的动作。
FuldeKeyboardKeyAction action;

FuldeKeyboardKeyType

虚拟键盘键的类型。

// 可以是动作键 - 返回、退格等。
FuldeKeyboardKeyType.Action
// 具有文本值的键 - 字母、数字、逗号等。
FuldeKeyboardKeyType.String

FuldeKeyboardKeyAction

虚拟键盘动作。

/// 虚拟键盘动作。
enum FuldeKeyboardKeyAction { Backspace, Return, Shift, Space }

使用方法

显示字母数字键盘(默认视图)

Container(
    // 背景颜色
    color: Colors.deepPurple,
    child: FuldeKeyboard(
        // 默认高度300
        height: 350,
        // 宽度为屏幕宽度
        width: 600,
        // 文字颜色默认为黑色
        textColor: Colors.white,
        // 字体大小默认为14
        fontSize: 20,
        // 支持的布局
        defaultLayouts: [FuldeKeyboardDefaultLayouts.English],
        // [A-Z, 0-9]
        type: FuldeKeyboardType.Alphanumeric,
        // 按键事件回调
        onKeyPress: _onKeyPress),
)

显示数字键盘(默认视图)

Container(
    // 背景颜色
    color: Colors.red,
    child: FuldeKeyboard(
        // [0-9] + .
        type: FuldeKeyboardType.Numeric,
        // 按键事件回调
        onKeyPress: (key) => print(key.text)),
)

显示字母数字键盘(自定义按键)

Container(
    color: Colors.deepPurple,
    child: FuldeKeyboard(
        height: keyboardHeight,
        textColor: Colors.white,
        fontSize: 20,
        builder: _builder,
        type: FuldeKeyboardType.Numeric,
        onKeyPress: _onKeyPress),
)

/// 自定义按键构建器。
Widget _builder(BuildContext context, FuldeKeyboardKey key) {
    Widget keyWidget;

    switch (key.keyType) {
        case FuldeKeyboardKeyType.String:
            // 绘制字符串键。
            keyWidget = _keyboardDefaultKey(key);
            break;
        case FuldeKeyboardKeyType.Action:
            // 绘制动作键。
            keyWidget = _keyboardDefaultActionKey(key);
            break;
    }

    return keyWidget;
}

onKeyPressed 事件基本使用示例

// 仅用于局部变量。使用Text小部件或其他类似方式在UI中显示。
String text;

/// 当虚拟键盘按键被按下时触发。
_onKeyPress(FuldeKeyboardKey key) {
    if (key.keyType == FuldeKeyboardKeyType.String) {
        text = text + (shiftEnabled ? key.capsText : key.text);
    } else if (key.keyType == FuldeKeyboardKeyType.Action) {
        switch (key.action) {
            case FuldeKeyboardKeyAction.Backspace:
                if (text.length == 0) return;
                text = text.substring(0, text.length - 1);
                break;
            case FuldeKeyboardKeyAction.Return:
                text = text + '\n';
                break;
            case FuldeKeyboardKeyAction.Space:
                text = text + key.text;
                break;
            case FuldeKeyboardKeyAction.Shift:
                shiftEnabled = !shiftEnabled;
                break;
            default:
        }
    }
    // 更新屏幕
    setState(() {});
}

完整示例代码

以下是完整的示例代码,展示如何使用 fulde_keyboard 插件来创建一个简单的应用:

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

void main() => runApp(const MyApp());

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fulde Keyboard Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(
        title: 'Fulde Keyboard Demo',
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  [@override](/user/override)
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  // 保存用户输入的文本。
  String text = '';
  // 是否启用大写。
  bool shiftEnabled = false;

  // 是否显示数字键盘。
  bool isNumericMode = false;
  bool isAltMode = false;
  late TextEditingController _controllerText;

  [@override](/user/override)
  void initState() {
    _controllerText = TextEditingController();
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
              text,
              style: Theme.of(context)
                  .textTheme
                  .bodyLarge
                  ?.copyWith(fontFamily: 'Fulde', fontSize: 40.0),
            ),
            Text(
              _controllerText.text,
              style: const TextStyle(
                  color: Colors.red, fontSize: 40.0, fontFamily: 'Fulde'),
            ),
            Expanded(
              child: Container(),
            ),
            Container(
              color: const Color(0xFF28282B),
              child: FuldeKeyboard(
                height: 200,
                // width: 100,
                textColor: Colors.white,
                textController: _controllerText,
                // customLayoutKeys: _customLayoutKeys,
                defaultLayouts: const [
                  FuldeKeyboardDefaultLayouts.fulde,
                  FuldeKeyboardDefaultLayouts.latin,
                  FuldeKeyboardDefaultLayouts.english
                ],
                // reverseLayout: true,
                type: FuldeKeyboardType.alphanumeric,
                onKeyPress: _onKeyPress,
                onTextDirectionChanged: (TextDirection value) {},
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 当虚拟键盘按键被按下时触发。
  _onKeyPress(FuldeKeyboardKey key) {
    if (key.keyType == FuldeKeyboardKeyType.string) {
      text = text + (shiftEnabled ? key.capsText : key.text).toString();
    } else if (key.keyType == FuldeKeyboardKeyType.action) {
      switch (key.action) {
        case FuldeKeyboardKeyAction.backspace:
          if (text.isEmpty) return;
          text = text.substring(0, text.length - 1);
          break;
        case FuldeKeyboardKeyAction.enter:
          text = '$text\n';
          break;
        case FuldeKeyboardKeyAction.space:
          text = text + key.text.toString();
          break;
        case FuldeKeyboardKeyAction.leftShift:
        case FuldeKeyboardKeyAction.rightShift:
          shiftEnabled = !shiftEnabled;
          break;
        default:
      }
    }
    // 更新屏幕
    setState(() {});
  }
}

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

1 回复

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


当然,以下是如何在Flutter中使用自定义键盘插件fulde_keyboard的一个基本示例。请注意,这个插件可能是一个假想的或非常特定的插件,因为在实际Flutter生态系统中,fulde_keyboard并不是一个广为人知的插件。不过,我会根据常见的自定义键盘插件的使用方式给出一个示例。

首先,确保你已经在pubspec.yaml文件中添加了fulde_keyboard(假设它存在)的依赖项:

dependencies:
  flutter:
    sdk: flutter
  fulde_keyboard: ^x.y.z  # 替换为实际的版本号

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用自定义键盘插件:

  1. 导入插件

在你的Dart文件中导入fulde_keyboard插件。

import 'package:fulde_keyboard/fulde_keyboard.dart';
  1. 创建自定义键盘

你可以使用FuldeKeyboard小部件来创建自定义键盘。以下是一个简单的示例,展示如何在TextField下方添加一个自定义键盘。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fulde Keyboard Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: CustomKeyboardExample(),
        ),
      ),
    );
  }
}

class CustomKeyboardExample extends StatefulWidget {
  @override
  _CustomKeyboardExampleState createState() => _CustomKeyboardExampleState();
}

class _CustomKeyboardExampleState extends State<CustomKeyboardExample> {
  final TextEditingController _controller = TextEditingController();
  String _inputText = '';

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        TextField(
          controller: _controller,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'Enter text',
          ),
          onChanged: (value) {
            setState(() {
              _inputText = value;
            });
          },
        ),
        SizedBox(height: 16),
        FuldeKeyboard(
          onKeyPressed: (String key) {
            setState(() {
              _controller.value = _controller.value.copyWith(
                text: _controller.text + key,
                selection: TextSelection.fromPosition(
                  TextPosition(
                    affinity: TextAffinity.downstream,
                    offset: _controller.text.length,
                  ),
                ),
                composing: TextRange.empty,
              );
            });
          },
          // 你可以根据需要自定义键盘的布局和按键
          keyboardLayout: [
            ['1', '2', '3'],
            ['4', '5', '6'],
            ['7', '8', '9'],
            ['0', 'Backspace'], // 假设Backspace是一个特殊的键
          ],
          specialKeys: {
            'Backspace': Icon(Icons.backspace),
          },
          builder: (context, key, specialKey) {
            return specialKey != null
                ? GestureDetector(
                    onTap: () {
                      if (specialKey == 'Backspace') {
                        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,
                          );
                        }
                      }
                      onKeyPressed(specialKey);
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(color: Colors.grey),
                        ),
                      ),
                      child: Center(child: specialKey != null ? specialKey : Text(key)),
                    ),
                  )
                : GestureDetector(
                    onTap: () => onKeyPressed(key),
                    child: Container(
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(color: Colors.grey),
                        ),
                      ),
                      child: Center(child: Text(key)),
                    ),
                  );
          },
        ),
      ],
    );
  }
}

注意

  • 上面的代码是一个简化的示例,展示了如何创建一个带有基本功能的自定义键盘。
  • FuldeKeyboard小部件及其参数(如onKeyPressedkeyboardLayoutspecialKeysbuilder)是假设的,因为实际的fulde_keyboard插件可能有不同的API。
  • 你可能需要根据实际插件的文档调整代码。
  • builder函数用于自定义每个按键的UI和交互。

由于fulde_keyboard可能不是一个真实存在的插件,你可能需要找到一个实际的自定义键盘插件(如simple_keyboard或其他)并参考其文档来实现类似的功能。

回到顶部