Flutter MAC 增加 shift+ enter 换行 enter 发送的键盘功能

40 min read

这个功能不是 Flutter 自带的,需要在 App 中自定义键盘行为。

可以使用 RawKeyboardListener 组件监听键盘事件,然后根据按键组合来执行不同的操作。

具体实现可以参考以下示例代码:

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

class CustomKeyboard extends StatefulWidget {
  @override
  _CustomKeyboardState createState() => _CustomKeyboardState();
}

class _CustomKeyboardState extends State<CustomKeyboard> {
  TextEditingController _textController;
  FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
    _focusNode = FocusNode();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Keyboard Example'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _textController,
              focusNode: _focusNode,
              keyboardType: TextInputType.multiline,
              maxLines: null,
              decoration: InputDecoration(
                labelText: 'Type something here',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16.0),
            RawKeyboardListener(
              focusNode: _focusNode,
              onKey: (RawKeyEvent event) {
                if (event is RawKeyDownEvent) {
                  if (event.logicalKey == LogicalKeyboardKey.enter ||
                      event.logicalKey == LogicalKeyboardKey.numpadEnter) {
                    if (event.isShiftPressed) {
                      _textController.value = TextEditingValue(
                        text: '${_textController.text}\n',
                      );
                    } else {
                      // Send message
                      _sendMessage();
                    }
                  }
                }
              },
              child: Container(),
            ),
          ],
        ),
      ),
    );
  }

  void _sendMessage() {
    // Handle send message
    print('Message sent: ${_textController.text}');
    _textController.clear();
  }
}

在上面的代码中,我们监听了 RawKeyDownEvent 事件,判断了按下的键是否为 enter 或 numpadEnter,并检查 shift 键是否被按下。

如果 shift 键被按下,则在当前文本框中插入一个换行符;否则,我们通过调用 _sendMessage 方法来处理发送消息的逻辑。

当用户在文本框中按下 enter 键时,系统会默认调用 TextField 的 onSubmitted 方法,但这个方法不支持 shift + enter 换行的功能,因此我们需要自定义键盘行为。