List of features I need from my TextField
- It should be multiline, default is single line
- It should submit on pressing Enter key or Send button
- It should expand automatically when text is added to it
- It should autofocus
- I can use SHIFT+ENTER to add new line without submitting the text
The below mentioned widget class fullfills all my above mentioned features
final TextEditingController textFieldController = TextEditingController();
class TextInputsWidget extends StatelessWidget {
const TextInputsWidget({Key? key}) : super(key: key);
void sendMessage() {
if (textFieldController.text.isNotEmpty) {
// send this to the server.
print(textFieldController.text);
chatTextFieldController.clear();
}
}
@override
Widget build(BuildContext context) {
return Expanded(
/// 5. I can use SHIFT+ENTER to add new line without submitting the text
child: RawKeyboardListener(
//for physical keyboard press
focusNode: FocusNode(),
onKey: (RawKeyEvent event) {
if (event.isShiftPressed &&
event.logicalKey == LogicalKeyboardKey.enter) {
// ignore
} else if (event.logicalKey == LogicalKeyboardKey.enter) {
sendMessage();
}
},
child: TextField(
scrollPhysics: ScrollPhysics(),
/// 1. It should be multiline
keyboardType: TextInputType.multiline,
/// 3. It should expand automatically when text is added to it
maxLines: null,
/// 2. It should submit on pressing Send
textInputAction: TextInputAction.send,
/// 4. It should autofocus
autofocus: true,
/// 2. It should submit on pressing Enter key
onSubmitted: (val) => sendMessage(),
controller: textFieldController,
decoration: const InputDecoration(
hintText: "Write message...",
hintStyle: TextStyle(color: Colors.black54),
focusColor: Colors.amber,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
),
),
));
}
}
Wrap the textfield around RawKeyboardListener to listen to keyboard events and filter our SHIFT+ENTER
Leave a Reply