我正在寻找一种方法来克服颤振Textfiend上/下键的行为。
当前,它们将光标移动到文本字段的开头或结尾。
我想更改此行为。我乐于接受任何可能性。
我研究了用RawKeyboardListener包装文本字段,但是向上/向下键事件仍然落入文本字段。
答案 0 :(得分:0)
星期六有趣的问题,花了我的空闲时间:) 发现我们可以为任何键获取UP和DOWN事件。 下面的示例在按向上箭头时将光标向后移动3个字母。
代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: KeyboardListener(),
);
}
}
class KeyboardListener extends StatefulWidget {
KeyboardListener();
@override
_RawKeyboardListenerState createState() => _RawKeyboardListenerState();
}
class _RawKeyboardListenerState extends State<KeyboardListener> {
TextEditingController _controller = TextEditingController();
FocusNode _textNode = FocusNode();
String _keyPressed = 'Key pressed code: ';
@override
initState() {
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
FocusScope.of(context).requestFocus(_textNode);
return Scaffold(
appBar: AppBar(title: Text("Search Item")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RawKeyboardListener(
focusNode: _textNode,
key: UniqueKey(),
onKey: handleKey,
child: TextField(
key: UniqueKey(),
controller: _controller,
),
),
SizedBox(
height: 20.0,
),
Text(_keyPressed),
],
),
);
}
handleKey(RawKeyEvent key) {
if (key.runtimeType.toString() == 'RawKeyUpEvent') {
RawKeyEventDataAndroid data = key.data as RawKeyEventDataAndroid;
String _keyCode;
_keyCode = data.keyCode.toString();
print(_keyCode);
if (_keyCode == '19') {
print('up pressed');
_controller.selection =
TextSelection.collapsed(offset: _controller.text.length - 3);
}
}
}
}