OnKeyDown event not updating instantly, OnKeyUp is

Issue

I just started looking at Dart. I am updating a <p> tag when editing an <input type="form">.

However, when I use the onKeyDown event, it is not updating instantly but is delayed by 1 keypress. So if I press AAA it will only display AA.

If I use onKeyUp, AAA will give me AAA.

Why is it not updating as expecting when using onKeyDown?

Here is the code:

import 'dart:html';

TextInputElement inputText;
ParagraphElement pargraphText;

void main() {
  inputText = querySelector("#text");
  pargraphText = querySelector("#paragraphText");

  // inputText.onKeyDown.listen(updateTekst);
  inputText.onKeyUp.listen(updateTekst);
}

void updateTekst(Event e) {
  pargraphText.text = inputText.value.toUpperCase();
}

Solution

That is because the input element doesn’t have the value yet. It gets the value on keyPress or keyUp but not yet on keyDown.
If you use the value from the event instead from the input field, then you get the value even for the first keyDown.

You can use e.keyCode (charCode is not set on keyDown)

import 'dart:convert';

...

// doesn't distinguish between upper/lower case (you have to check e.shiftKey)
UTF8.decode([e.keyCode]); 

Answered By – Günter Zöchbauer

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *