Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the character typed by the user

I want to process the characters typed by the user for a game (I don't want to use an input tag with a submit button).

I managed to get the keyCode typed with this code:

window.on.keyPress.add((Event e) 
{
    window.alert('${e.keyCode},${e.keyIdentifier},${e.charCode}');

});

but I don't know how to display the character of the key pressed (or even get the character of the key as a string). In Javascript there is a fromKeyCode() function but not in Dart.

Anyway, I am looking for the simplest way to get the keyboard inputs for processing and I would prefer not have to fiddle with keycodes and such.

like image 967
sai Avatar asked Dec 10 '25 14:12

sai


2 Answers

String.fromCharCodes() is gone

import 'dart:convert';

String result = UTF8.decode([e.charCode]); // or [e.keyCode]
like image 144
Günter Zöchbauer Avatar answered Dec 13 '25 14:12

Günter Zöchbauer


You can construct a new string from the character code with String.fromCharCodes().

var str = new String.fromCharCodes([e.charCode]);

However it's certainly not the most efficient to be creating a new string each time a user hits a key depending on your game. If you only expect a few specific characters to be hit and ignore others then you may want to create constant/final variables of character codes to compare the character code from the event.

final E_KEY = "e".charCodeAt(0);
// ... etc.

Keep in mind these don't account for various situations such a capitalization, or the CTRL or ALT or meta key pressed, etc.

like image 37
Matt B Avatar answered Dec 13 '25 15:12

Matt B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!