Skip to content

KeyEvent ​

class KeyEvent extends _WrappedEvent implements KeyboardEvent, Event

A custom KeyboardEvent that attempts to eliminate cross-browser inconsistencies, and also provide both keyCode and charCode information for all key events (when such information can be determined).

KeyEvent tries to provide a higher level, more polished keyboard event information on top of the "raw" KeyboardEvent.

The mechanics of using KeyEvents is a little different from the underlying KeyboardEvent. To use KeyEvents, you need to create a stream and then add KeyEvents to the stream, rather than using the EventTarget.dispatchEvent. Here's an example usage:

dart
// Initialize a stream for the KeyEvents:
var stream = KeyEvent.keyPressEvent.forTarget(document.body);
// Start listening to the stream of KeyEvents.
stream.listen((keyEvent) =>
    window.console.log('KeyPress event detected ${keyEvent.charCode}'));
...
// Add a new KeyEvent of someone pressing the 'A' key to the stream so
// listeners can know a KeyEvent happened.
stream.add(new KeyEvent('keypress', keyCode: 65, charCode: 97));

This class is very much a work in progress, and we'd love to get information on how we can make this class work with as many international keyboards as possible. Bugs welcome!

Implemented types

Constructors ​

KeyEvent() factory ​

factory KeyEvent(
  String type, {
  Window? view,
  bool canBubble = true,
  bool cancelable = true,
  int keyCode = 0,
  int charCode = 0,
  int location = 1,
  bool ctrlKey = false,
  bool altKey = false,
  bool shiftKey = false,
  bool metaKey = false,
  EventTarget? currentTarget,
})

Programmatically create a new KeyEvent (and KeyboardEvent).

Implementation
dart
factory KeyEvent(
  String type, {
  Window? view,
  bool canBubble = true,
  bool cancelable = true,
  int keyCode = 0,
  int charCode = 0,
  int location = 1,
  bool ctrlKey = false,
  bool altKey = false,
  bool shiftKey = false,
  bool metaKey = false,
  EventTarget? currentTarget,
}) {
  if (view == null) {
    view = window;
  }

  KeyboardEvent eventObj;

  // Currently this works on everything but Safari. Safari throws an
  // "Attempting to change access mechanism for an unconfigurable property"
  // TypeError when trying to do the Object.defineProperty hack, so we avoid
  // this branch if possible.
  // Also, if we want this branch to work in FF, we also need to modify
  // _initKeyboardEvent to also take charCode and keyCode values to
  // initialize initKeyEvent.

  eventObj =
      new Event.eventType(
            'KeyboardEvent',
            type,
            canBubble: canBubble,
            cancelable: cancelable,
          )
          as KeyboardEvent;

  // Chromium Hack
  JS(
    'void',
    "Object.defineProperty(#, 'keyCode', {"
        "  get : function() { return this.keyCodeVal; } })",
    eventObj,
  );
  JS(
    'void',
    "Object.defineProperty(#, 'which', {"
        "  get : function() { return this.keyCodeVal; } })",
    eventObj,
  );
  JS(
    'void',
    "Object.defineProperty(#, 'charCode', {"
        "  get : function() { return this.charCodeVal; } })",
    eventObj,
  );

  var keyIdentifier = _convertToHexString(charCode, keyCode);
  eventObj._initKeyboardEvent(
    type,
    canBubble,
    cancelable,
    view,
    keyIdentifier,
    location,
    ctrlKey,
    altKey,
    shiftKey,
    metaKey,
  );
  JS('void', '#.keyCodeVal = #', eventObj, keyCode);
  JS('void', '#.charCodeVal = #', eventObj, charCode);

  // Tell dart2js that it smells like a KeyboardEvent!
  setDispatchProperty(eventObj, _keyboardEventDispatchRecord);

  var keyEvent = new KeyEvent.wrap(eventObj);
  if (keyEvent._currentTarget == null) {
    keyEvent._currentTarget = currentTarget == null ? window : currentTarget;
  }
  return keyEvent;
}

KeyEvent.wrap() ​

KeyEvent.wrap(KeyboardEvent parent)

Construct a KeyEvent with parent as the event we're emulating.

Implementation
dart
KeyEvent.wrap(KeyboardEvent parent)
  : _parent = parent,
    _shadowAltKey = false,
    _shadowCharCode = 0,
    _shadowKeyCode = 0,
    super(parent) {
  _parent = parent;
  _shadowAltKey = _realAltKey;
  _shadowCharCode = _realCharCode;
  _shadowKeyCode = _realKeyCode;
  _currentTarget = _parent.currentTarget;
}

Properties ​

altKey no setter override ​

bool get altKey

Calculated value of whether the alt key is pressed is for this event.

Implementation
dart
bool get altKey => _shadowAltKey;

bubbles no setter inherited ​

bool get bubbles

Inherited from _WrappedEvent.

Implementation
dart
bool get bubbles => wrapped.bubbles!;

cancelable no setter inherited ​

bool get cancelable

Inherited from _WrappedEvent.

Implementation
dart
bool get cancelable => wrapped.cancelable!;

charCode no setter override ​

int get charCode

Calculated value of what the estimated charCode is for this event.

Implementation
dart
int get charCode => this.type == 'keypress' ? _shadowCharCode : 0;

code no setter override ​

String get code
Implementation
dart
String get code => _parent.code!;

composed no setter inherited ​

bool get composed

Inherited from _WrappedEvent.

Implementation
dart
bool get composed => wrapped.composed!;

ctrlKey no setter override ​

bool get ctrlKey

True if the ctrl key is pressed during this event.

Implementation
dart
bool get ctrlKey => _parent.ctrlKey;

currentTarget no setter ​

EventTarget? get currentTarget

The currently registered target for this event.

Implementation
dart
EventTarget? get currentTarget => _currentTarget;

defaultPrevented no setter inherited ​

bool get defaultPrevented

Inherited from _WrappedEvent.

Implementation
dart
bool get defaultPrevented => wrapped.defaultPrevented;

detail no setter override ​

int get detail
Implementation
dart
int get detail => _parent.detail!;

eventPhase no setter inherited ​

int get eventPhase

Inherited from _WrappedEvent.

Implementation
dart
int get eventPhase => wrapped.eventPhase;

hashCode no setter inherited ​

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

isComposed no setter ​

bool get isComposed
Implementation
dart
bool get isComposed => throw new UnimplementedError();

isComposing no setter override ​

bool get isComposing
Implementation
dart
bool get isComposing => _parent.isComposing!;

isTrusted no setter inherited ​

bool get isTrusted

Inherited from _WrappedEvent.

Implementation
dart
bool get isTrusted => wrapped.isTrusted!;

key no setter override ​

String get key
Implementation
dart
String get key => _parent.key!;

keyCode no setter override ​

int get keyCode

Calculated value of what the estimated keyCode is for this event.

Implementation
dart
int get keyCode => _shadowKeyCode;

location no setter override ​

int get location

Accessor to the part of the keyboard that the key was pressed from (one of KeyLocation.STANDARD, KeyLocation.RIGHT, KeyLocation.LEFT, KeyLocation.NUMPAD, KeyLocation.MOBILE, KeyLocation.JOYSTICK).

Implementation
dart
int get location => _parent.location;

matchingTarget no setter inherited ​

Element get matchingTarget

Inherited from _WrappedEvent.

Implementation
dart
Element get matchingTarget {
  if (_selector == null) {
    throw new UnsupportedError(
      'Cannot call matchingTarget if this Event did'
      ' not arise as a result of event delegation.',
    );
  }
  Element? currentTarget = this.currentTarget as Element?;
  Element? target = this.target as Element?;
  do {
    if (target!.matches(_selector!)) return target;
    target = target.parent;
  } while (target != null && target != currentTarget!.parent);
  throw new StateError('No selector matched for populating matchedTarget.');
}

metaKey no setter override ​

bool get metaKey

True if the Meta (or Mac command) key is pressed during this event.

Implementation
dart
bool get metaKey => _parent.metaKey;

path no setter inherited ​

List<Node> get path

Inherited from _WrappedEvent.

Implementation
dart
&#47;&#47; https:&#47;&#47;dvcs.w3.org&#47;hg&#47;webcomponents&#47;raw-file&#47;tip&#47;spec&#47;shadow&#47;index.html#extensions-to-event
List<Node> get path => wrapped.path as List<Node>;

repeat no setter override ​

bool get repeat
Implementation
dart
bool get repeat => throw new UnimplementedError();

runtimeType no setter inherited ​

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

shiftKey no setter override ​

bool get shiftKey

True if the shift key was pressed during this event.

Implementation
dart
bool get shiftKey => _parent.shiftKey;

sourceCapabilities no setter override ​

InputDeviceCapabilities? get sourceCapabilities
Implementation
dart
InputDeviceCapabilities? get sourceCapabilities =>
    JS('InputDeviceCapabilities', '#.sourceCapabilities', this);

target no setter inherited ​

EventTarget? get target

Inherited from _WrappedEvent.

Implementation
dart
EventTarget? get target => wrapped.target;

timeStamp no setter inherited ​

double get timeStamp

Inherited from _WrappedEvent.

Implementation
dart
double get timeStamp => wrapped.timeStamp as double;

type no setter inherited ​

String get type

Inherited from _WrappedEvent.

Implementation
dart
String get type => wrapped.type;

view no setter override ​

WindowBase? get view
Implementation
dart
WindowBase? get view => _parent.view;

which no setter override ​

int get which

Calculated value of what the estimated keyCode is for this event.

Implementation
dart
int get which => keyCode;

wrapped final inherited ​

final Event wrapped

Inherited from _WrappedEvent.

Implementation
dart
final Event wrapped;

Methods ​

composedPath() inherited ​

List<EventTarget> composedPath()

Inherited from _WrappedEvent.

Implementation
dart
List<EventTarget> composedPath() => wrapped.composedPath();

getModifierState() override ​

bool getModifierState(String keyArgument)
Implementation
dart
bool getModifierState(String keyArgument) => throw new UnimplementedError();

noSuchMethod() inherited ​

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

preventDefault() inherited ​

void preventDefault()

Inherited from _WrappedEvent.

Implementation
dart
void preventDefault() {
  wrapped.preventDefault();
}

stopImmediatePropagation() inherited ​

void stopImmediatePropagation()

Inherited from _WrappedEvent.

Implementation
dart
void stopImmediatePropagation() {
  wrapped.stopImmediatePropagation();
}

stopPropagation() inherited ​

void stopPropagation()

Inherited from _WrappedEvent.

Implementation
dart
void stopPropagation() {
  wrapped.stopPropagation();
}

toString() inherited ​

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators ​

operator ==() inherited ​

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);

Static Properties ​

canUseDispatchEvent no setter ​

bool get canUseDispatchEvent
Implementation
dart
static bool get canUseDispatchEvent => JS(
  'bool',
  '(typeof document.body.dispatchEvent == "function")'
      '&& document.body.dispatchEvent.length > 0',
);

keyDownEvent read / write ​

getter:

Accessor to provide a stream of KeyEvents on the desired target.

setter:

Accessor to provide a stream of KeyEvents on the desired target.

Implementation
dart
static EventStreamProvider<KeyEvent> keyDownEvent = new _KeyboardEventHandler(
  'keydown',
);

keyPressEvent read / write ​

getter:

Accessor to provide a stream of KeyEvents on the desired target.

setter:

Accessor to provide a stream of KeyEvents on the desired target.

Implementation
dart
static EventStreamProvider<KeyEvent> keyPressEvent =
    new _KeyboardEventHandler('keypress');

keyUpEvent read / write ​

getter:

Accessor to provide a stream of KeyEvents on the desired target.

setter:

Accessor to provide a stream of KeyEvents on the desired target.

Implementation
dart
static EventStreamProvider<KeyEvent> keyUpEvent = new _KeyboardEventHandler(
  'keyup',
);