Flutter键盘输入监测插件keyboard_typing的使用

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

Flutter键盘输入监测插件keyboard_typing的使用

安装插件
flutter pub add keyboard_typing
导入包
import 'package:keyboard_typing/keyboard_typing.dart';

更新

0.0.7 版本

如果你定义了 cursorStyle 参数,你可以在 TextWidget 旁边看到光标(caret)。

CursorStyle 📍
参数 必填 类型 默认值
mode ✔️ KeyboardTypingCursorMode none
color Color?
width double 1.0
KeyboardTyping(
  text: Text("KeyboardTyping Test Sentence"),
  controller: controller,
  cursorStyle: CursorStyle(
    mode: KeyboardTypingCursorMode.vertical
  )
)

GIF

使用

如果你不定义一个 KeyboardTypingControllerKeyboardTyping 小部件将自动播放。

创建 KeyboardTyping 小部件 ⌨

参数 必填 类型 默认值
text ✔️ Text
controller KeyboardTypingController?
previewTextColor Color?
mode KeyboardTypingMode normal
intervalDuration Duration? Duration(milliseconds: 150)
cursorStyle CursorStyle? CursorStyle(mode: KeyboardTypingCursorMode.none)
KeyboardTyping(
  text: Text("Something Text"),
)

播放打字动画 🚩

// 自动播放
KeyboardTypingController controller = KeyboardTypingController();

[@override](/user/override)
void initState() {
  controller
    ..addStateEventListener(keyboardStateEventListener)
    ..play();
}
// 用户控制
[@override](/user/override)
Widget build(BuildContext context) {
  ...
  ElevatedButton(
    onPressed: () {
      controller.play();
    }
  )
}

停止打字动画 🚧

如果你想清除文本,可以将 cancel 参数设为 true

KeyboardTypingController controller = KeyboardTypingController();

[@override](/user/override)
Widget build(BuildContext context) {
  ...
  ElevatedButton(
    onPressed: () {
      // 正常停止
      controller.stop();

      // 强制停止
      controller.stop(cancel: true);    // 效果是清除文本并重新开始。
    }
  )
}

重复打字动画 🌀

KeyboardTyping(
  text: Text("Something Text"),
  mode: KeyboardTypingMode.repeat,
)

监听打字事件状态 🎈

controller.addStateEventListener((KeyboardTypingState state) {
  setState(() {
    switch (state) {
      case KeyboardTypingState.idle:
        // TODO: 处理这种情况。
      case KeyboardTypingState.active:
        // TODO: 处理这种情况。
      case KeyboardTypingState.pause:
        // TODO: 处理这种情况。
      case KeyboardTypingState.stop:
        // TODO: 处理这种情况。
      case KeyboardTypingState.complete:
        // TODO: 处理这种情况。
    }
  });
},);

// 移除
// controller.removeStateEventListener(...);

预览文本 👥

0.0.6 版本

如果你定义了 previewTextColor 参数,你可以看到预览 TextWidget 的数据。

KeyboardTyping(
  text: Text("If you define 'previewTextColor' parameter,\nThen you can see a preview TextWidget :)"),
  previewTextColor: Colors.grey.withOpacity(0.5),
)

完整示例 Demo

以下是完整的示例代码:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_logcat/flutter_logcat.dart';
import 'package:keyboard_typing/keyboard_typing.dart';

void main() {
  Log.configure(visible: kDebugMode);

  runApp(const MyApp());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Typing Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Typing Demo 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 KeyboardTypingController controller = KeyboardTypingController();
  final KeyboardTypingController controllerRepeat = KeyboardTypingController();
  final KeyboardTypingController controllerAutoStart = KeyboardTypingController();
  late String state;
  late String stateRepeat;
  bool isCursorVisible = true;

  [@override](/user/override)
  void initState() {
    super.initState();
    state = controller.state.name.toUpperCase();
    stateRepeat = controllerRepeat.state.name.toUpperCase();

    controller.addStateEventListener((state) {
      Log.i("StateEventListener.. state:$state");
      setState(() {
        this.state = state.name.toUpperCase();
      });
    },);

    controllerRepeat..addStateEventListener((state) {
      Log.x("StateEventListener.. stateRepeat:$state");
      setState(() {
        stateRepeat = state.name.toUpperCase();
      });
    },);

    controllerAutoStart.play();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            KeyboardTyping(
              text: Text("Only TextWidget,\n Not define KeyboardTypingController :)"),
              // cursorMode: KeyboardTypingCursorMode.none,
            ),
            const SizedBox(height: 36.0,),
            Container(
              color: Colors.green,
              child: KeyboardTyping(
                text: Text("If you define 'previewTextColor' parameter,\nThen you can see a preview TextWidget :)",
                ),
                previewTextColor: Colors.grey.withOpacity(0.5),
              ),
            ),
            const SizedBox(height: 18.0,),
            KeyboardTyping(
              text: Text(
                  'You have pressed the Start Button and Typing action! '
                  'also pressed the Stop Button and stop Typing action!',
                style: TextStyle(
                  color: Colors.green[900],
                  fontSize: 24.0
                ),
              ),
              controller: controller,
              intervalDuration: const Duration(milliseconds: 50),
            ),
            const SizedBox(height: 18.0,),
            Text(state,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            const SizedBox(height: 24.0,),
            KeyboardTyping(
              text: Text("You have pressed the Repeat Button and Typing action!",
                style: TextStyle(
                  fontSize: 21.0,
                  color: Colors.blue[900],
                ),
              ),
              controller: controllerRepeat,
              mode: KeyboardTypingMode.repeat,
              previewTextColor: Colors.grey.withOpacity(0.7),
            ),
            const SizedBox(height: 18.0,),
            Text(stateRepeat,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            const SizedBox(height: 18.0,),
            KeyboardTyping(
              text: Text("Added AutoStart KeyboardTyping Animation when you add controller parameter"),
              controller: controllerAutoStart,
            ),
          ],
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                key: null,
                onPressed: () {
                  setState(() {
                    isCursorVisible = !isCursorVisible;
                    controller.cursor(visible: isCursorVisible);
                    controllerRepeat.cursor(visible: isCursorVisible);
                  });
                },
                child: Text("Cursor\n$isCursorVisible",
                  textAlign: TextAlign.center,
                ),
              ),
              const SizedBox(width: 16.0,),
              FloatingActionButton(
                key: null,
                onPressed: () {
                  setState(() {
                    controller.play();
                    controllerRepeat.play();
                  });
                },
                child: const Text("Play"),
              ),
            ],
          ),
          const SizedBox(height: 16.0,),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                key: null,
                onPressed: () {
                  setState(() {
                    controller.stop();
                    controllerRepeat.stop();
                  });
                },
                child: const Text("Stop"),
              ),
              const SizedBox(width: 16.0,),
              FloatingActionButton(
                key: null,
                onPressed: () {
                  setState(() {
                    controller.stop(cancel: true);
                    controllerRepeat.stop(cancel: true);
                  });
                },
                child: const Text("Forced\nStop",
                  textAlign: TextAlign.center,
                ),
              )
            ],
          ),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

更多关于Flutter键盘输入监测插件keyboard_typing的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter键盘输入监测插件keyboard_typing的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用keyboard_typing插件来监测键盘输入的示例代码。这个插件允许你监听文本框的输入事件,获取用户输入的字符、删除字符等事件。

首先,你需要在你的pubspec.yaml文件中添加keyboard_typing依赖:

dependencies:
  flutter:
    sdk: flutter
  keyboard_typing: ^0.4.0  # 请确保使用最新版本,这里版本号为示例

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

接下来,你可以在你的Flutter项目中使用KeyboardTypingPlugin来监听键盘输入事件。以下是一个完整的示例代码,展示如何设置和使用这个插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Keyboard Typing Example'),
        ),
        body: TypingDetectorExample(),
      ),
    );
  }
}

class TypingDetectorExample extends StatefulWidget {
  @override
  _TypingDetectorExampleState createState() => _TypingDetectorExampleState();
}

class _TypingDetectorExampleState extends State<TypingDetectorExample> {
  final KeyboardTypingController _keyboardController = KeyboardTypingController();

  @override
  void initState() {
    super.initState();
    // 初始化监听器
    _keyboardController.addListener(_onKeyboardTyping);
  }

  @override
  void dispose() {
    // 移除监听器
    _keyboardController.removeListener(_onKeyboardTyping);
    super.dispose();
  }

  void _onKeyboardTyping(KeyboardTypingEvent event) {
    // 处理键盘输入事件
    print('键盘事件: ${event.eventType}');
    print('输入字符: ${event.text}');
    print('光标位置: ${event.cursorPosition}');
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextField(
            decoration: InputDecoration(
              labelText: '输入文本',
            ),
            onChanged: (text) {
              // 这里通常不需要处理 onChange,因为 KeyboardTypingController 已经监听
            },
            controller: TextEditingController()..addListener(() {
              // 手动触发键盘事件(如果需要的话,但通常不需要)
              // 这里的实现可以根据你的需求进行调整
            }),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              // 你可以在这里调用其他与键盘输入相关的逻辑
              // 例如:重置输入状态,显示提示信息等
              print('按钮被点击');
            },
            child: Text('按钮'),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. pubspec.yaml中添加了keyboard_typing依赖。
  2. 创建了一个Flutter应用,并在主页中使用TextField来接收用户输入。
  3. 使用KeyboardTypingController来监听键盘输入事件,并在_onKeyboardTyping方法中处理这些事件。
  4. initState方法中添加了监听器,在dispose方法中移除了监听器,以确保资源正确管理。

请注意,keyboard_typing插件的具体实现和API可能会根据版本有所不同,所以请务必查阅最新的官方文档和示例代码。如果你遇到任何问题,也可以查阅该插件的GitHub仓库或相关社区获取帮助。

回到顶部