11

Is there any way to catch a keypress in textfield? In my case, when the user press enter key inside the text field, the values will be stored. For this to happen, I need to use Keypress-event like in Kotlin+Android. I just started trying flutter this week since it is interesting and cross-platform.

RawKeyboardListener(
  child: TextFormField(
    keyboardType: TextInputType.text,
    decoration: new InputDecoration(labelText: "Phone"),
    validator: (val) => val.length == 0 ? 'Enter your phone' : null,
    onSaved: (val) => this.phone = val,
  ),
   focusNode: FocusNode(),
   onKey: (RawKeyEvent event) {
     print(event.data.logicalKey.keyId);
     if (event.runtimeType == RawKeyDownEvent ) {
       print("asdadda");

     }
   },
),

But I don't know why it doesn't work however I press key.

kinesis
  • 373
  • 1
  • 4
  • 15

5 Answers5

18

As Alok suggested, I looked into onSubmitted method. I use TextfromField, so I choose onFieldSubmitted method in my case. And I also added RawKeyBoardListener for physical Enter key press from mobile scanner device. And the code is -

RawKeyboardListener(//for physical keyboard press
              child: TextFormField(
                keyboardType: TextInputType.text,
                decoration: new InputDecoration(labelText: "Phone"),
                validator: (val) => val.length == 0 ? 'Enter your phone' : null,
                onSaved: (val) => this.phone = val,
                onFieldSubmitted: (_) async {
                  print("asdadda");
                  submitContact();
                },
              ),
               focusNode: FocusNode(),
               onKey: (RawKeyEvent event) { 
                 print(event.data.logicalKey.keyId);
                 if (event.runtimeType == RawKeyDownEvent  &&
                     (event.logicalKey.keyId == 4295426088))//Enter Key ID from keyboard
                 {
                   print("asdadda");
                   submitContact();
                 }
               },
            ),

Feel free to edit ^_^

kinesis
  • 373
  • 1
  • 4
  • 15
12

I am sure what you're looking for is TextField's onSubmitted. What does this do is, on press of Enter on your keyboard, it gives you the value, which it takes as a param/args. For more info about this, you can checkout this: onSubmitted Property TextField

How you can do this, it is a property of TextField, you just have to simply do this to get your task done.

You can also do anything inside this property.

TextField(
  onSubmitted: (value){ 
     print(value);
     // or do whatever you want when you are done editing
     // call your method/print values etc
  }
)

Read more about TextField Class also. This will help you in many ways. Hope that will help you in your case. Happy learning :)

Alok
  • 8,452
  • 13
  • 55
  • 93
  • It does not work. onSubmitted is invoked in two cases: user presses 'Enter' and user moves focus to other field. I did not find a way to exclude focus change. – polina-c May 24 '20 at 20:22
  • Hey @polina-c, please look into this link: https://stackoverflow.com/a/49411314/5362583, this will answer your query. Happy learning :) – Alok May 25 '20 at 05:42
1

There are two ways to do 1). Using the onChanged method which comes with the TextField widget like this,

TextField(
  onChanged: (text) {
    print("First text field: $text");
  },
);

2). Use a TextEditingController

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Retrieve Text Input',
      home: MyCustomForm(),
    );
  }
}

// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();

  @override
  void initState() {
    super.initState();

    myController.addListener(_printLatestValue);
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the widget tree.
    // This also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  }

  _printLatestValue() {
    print("Second text field: ${myController.text}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              onChanged: (text) {
                print("First text field: $text");
              },
            ),
            TextField(
              controller: myController,
            ),
          ],
        ),
      ),
    );
  }
}

Example taken from the https://flutter.dev/docs/cookbook/forms/text-field-changes

Ropali Munshi
  • 2,757
  • 4
  • 22
  • 45
  • `onChanged()` method is not good for my case because this method performs everytime when the text change. For my case, the user types input and press enter to make changes. – kinesis Oct 07 '19 at 06:19
0

Just wrap your TextFormField with GestureDetector, then add event onTap:

GestureDetector(
    onTap: () {
      setState(() {
        // Add event here
      });
    },
    child: TextFormField(
      keyboardType: TextInputType.text,
      decoration: new InputDecoration(labelText: "Phone"),
      validator: (val) => val.length == 0 ? 'Enter your phone' : null,
      onSaved: (val) => this.phone = val,
    ),
  ),
hoangquyy
  • 1,893
  • 2
  • 14
  • 29
  • Acctually it work, but with other event like onDoubleTap, it not work because it focus on event of textformfield then it ignore onTap. Great to see that you have your answear – hoangquyy Oct 07 '19 at 08:09
  • You can use this in every widget that you want to add touch event if you want to. more tip for your flutter skill – hoangquyy Oct 07 '19 at 08:11
  • I can use this `onTap` method for `Icons` right? Thanks for further help. – kinesis Oct 07 '19 at 08:21
  • Yeah you can use it for every widget that can display on the screen – hoangquyy Oct 07 '19 at 08:22
0

Looks like you might be able to use KeyEventSimulator. Here is a link to some documentation: https://api.flutter.dev/flutter/flutter_test/simulateKeyDownEvent.html

Shalom Friss
  • 165
  • 1
  • 3