How to use Key Press Event on TextFormField in Flutter?
Asked Answered
C

5

12

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.

Choosey answered 7/10, 2019 at 4:43 Comment(3)
Try RawKeyboardListenerBrumby
Can I wrap the textview in RawKeyBoardListener?Choosey
no textview but TextField yesBrumby
T
13

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 :)

Tamarin answered 7/10, 2019 at 7:32 Comment(2)
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.Aleta
Hey @polina-c, please look into this link: https://mcmap.net/q/345174/-changing-focus-from-one-text-field-to-the-next-in-flutter, this will answer your query. Happy learning :)Tamarin
C
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 ^_^

Choosey answered 7/10, 2019 at 8:19 Comment(1)
Great to see you hands getting dirty in flutter. Keep going :)Tamarin
T
13

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 :)

Tamarin answered 7/10, 2019 at 7:32 Comment(2)
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.Aleta
Hey @polina-c, please look into this link: https://mcmap.net/q/345174/-changing-focus-from-one-text-field-to-the-next-in-flutter, this will answer your query. Happy learning :)Tamarin
K
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

Kalil answered 7/10, 2019 at 5:14 Comment(1)
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.Choosey
E
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,
    ),
  ),
Ellery answered 7/10, 2019 at 7:36 Comment(4)
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 answearEllery
You can use this in every widget that you want to add touch event if you want to. more tip for your flutter skillEllery
I can use this onTap method for Icons right? Thanks for further help.Choosey
Yeah you can use it for every widget that can display on the screenEllery
K
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

Knapsack answered 29/1, 2021 at 21:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.