Tracking mouse movement in Dart?


I wrote a basic program to get the mouse location on a canvas and it’s freezing my computer each time I run it, can someone take a look please? Also if you know a better way to do this, that’d be great.

I decided to learn this language because I don’t like JavaScript and I read it’s ideal for Java/C++ guys so that’s why I started this language.

import 'dart:html';
import 'dart:async';
import 'package:polymer/polymer.dart';

CanvasElement canvas = document.querySelector('#myPaintCanvas');
CanvasRenderingContext2D context = canvas.getContext('2d');

void pencil(mouseX, mouseY){
print("This is from pencil method: MouseX: " + mouseX.toString() + " MouseY: " + mouseY.toString());

void mouseDragginStarts(moveX, moveY){
print("This is from mouseDragging: " + "mouseX: "+ moveX + " mouseY:" + moveX);

void main(){
//get a refrence to the canvas

//canvas.onClick.listen((e) {
print("Got a click (${e.client.x-canvas.offsetLeft}, ${e.client.y-canvas.offsetTop})");
pencil(e.client.x-canvas.offsetLeft, e.client.y-canvas.offsetTop);

//while(canvas.onClick.listen(e) == true && canvas.onDrag.listen(e) == true){
while(canvas.onDrag == true){
  mouseDragginStarts(e.client.x, e.client.y);



/*context.moveTo(100, 150);
context.lineTo(450, 50);
context.lineWidth = 4;
//set the line color
context.strokeStyle = '#ff0000'; //red


while(canvas.onDrag == true){ <== I wonder if it enters the loop, canvas.onDrag never becomes true
  mouseDragginStarts(e.client.x, e.client.y);

  if(e==false){ <== e never becomes false

Your code doesn’t make any sense. You should start over by explaining what you actually try to accomplish.

When you only want to track mouse movement then you just do

canvas.onMouseMove.listen((e) {
  // do something with mouse coordinates
  // e.client.x, e.client.y

Answered By – Günter Zöchbauer

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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