如何解决在 TextField flutter 中包装文本而不创建换行符
使用 maxLines = null
属性,我可以使文本换行在 TextField
中。但是,这也使用 Enter
创建换行符。
我不想那样 - 我想将 Enter
键保留给 onSubmitted()
函数。我该怎么做?
解决方法
您可以使用 onKey
的 TextField
(FocusNode
) 或 WidgetOne
(RawKeyboardListener
) 的 WidgetTwo
实现此目的:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() {
runApp(
MaterialApp(
title: 'Wrapping Single Line Text Fields',home: _Page(),),);
}
class _Page extends HookWidget {
const _Page({
Key key,}) : super(key: key);
@override
Widget build(BuildContext context) {
final result = useState('');
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(32.0),child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,children: [
_WidgetOne(onSubmitted: (value) => result.value = value),_WidgetTwo(onSubmitted: (value) => result.value = value),Container(
margin: const EdgeInsets.all(15.0),padding: const EdgeInsets.all(3.0),decoration:
BoxDecoration(border: Border.all(color: Colors.black)),child: Text('Result: ${result.value}')),],);
}
}
class _WidgetOne extends StatelessWidget {
final ValueChanged<String> onSubmitted;
const _WidgetOne({Key key,this.onSubmitted}) : super(key: key);
@override
Widget build(BuildContext context) {
final _controller = TextEditingController();
final _focusNode = FocusNode(onKey: (node,event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
onSubmitted(_controller.text);
node.unfocus();
return true;
}
return false;
});
return TextField(
decoration: InputDecoration(hintText: 'With FocusNode onKey'),controller: _controller,focusNode: _focusNode,maxLines: null,);
}
}
class _WidgetTwo extends StatelessWidget {
final ValueChanged<String> onSubmitted;
const _WidgetTwo({Key key,event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
onSubmitted(_controller.text);
node.unfocus();
return true;
}
return false;
});
return RawKeyboardListener(
focusNode: _focusNode,onKey: (event) {
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
onSubmitted(_controller.text);
}
},child: TextField(
decoration: InputDecoration(hintText: 'With RawKeyboardListener onKey'),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。