touchEventToMouseEvent function
Converts a TouchEvent event
to a MouseEvent.
This helps to use TouchEvent as normal MouseEvent, simplifying UI support for touch events and mouse events.
Implementation
MouseEvent? touchEventToMouseEvent(TouchEvent event) {
var touches = event.touches;
if (touches.isEmpty) return null;
var first = touches.item(0)!;
var type = '';
switch (event.type.toLowerCase()) {
case 'touchstart':
type = 'mousedown';
break;
case 'touchmove':
type = 'mousemove';
break;
case 'touchend':
type = 'mouseup';
break;
default:
return null;
}
EventTarget? target;
// If `event.target` is null, not dispatched, it will throw an exception.
try {
target = event.target;
}
// ignore: empty_catches
catch (ignore) {}
var simulatedEvent = MouseEvent(
type,
MouseEventInit(
bubbles: event.bubbles,
cancelable: event.cancelable,
view: window,
detail: 1,
screenX: first.screenX.toInt(),
screenY: first.screenY.toInt(),
clientX: first.clientX.toInt(),
clientY: first.clientY.toInt(),
ctrlKey: event.ctrlKey,
altKey: event.altKey,
shiftKey: event.shiftKey,
metaKey: event.metaKey,
button: 0,
relatedTarget: target,
),
);
return simulatedEvent;
}