Albêr Albêr - 3 months ago 12
Dart Question

Understanding Dart's element events

I've started learning Dart and find one thing to be very confusing, namely events that are fired on an Element.

Say I have items in my template, which I wish to delete.

querySelector('.delete').onClick.listen((MouseEvent e) {
item_id = /* how do I get this value? */
});


<button class="delete" data-item="1">Delete</button>
<button class="delete" data-item="2">Delete</button>
...
<button class="delete" data-item="n">Delete</button>


How do I access said Element? How do I get its attributes? How do I find out which button was clicked, what value
data-item
had?

I've searched the docs, unfortunately I haven't been able to find anything that has led me in the right direction. I've encountered a method to get a Node object, but since an Element inherits from a Node, I can't really access that either.

Also, any books or great online sources to learn dart for front-end purposes are very much appreciated, as I've also found nothing

Answer

If you use querySelectorAll() you get an ElementList and can listen to click events of all delete elements at once.

querySelectorAll('.delete').onClick.listen((MouseEvent e) {
  print((e.target as HtmlElement).dataset['item']);
});

With e.target you get a reference to the clicked element. For autocompletion we cast to HtmlElement and by using it's dataset property we can access its data-... properties.

DartPad example

The console view shows the data-item value of each clicked element.

Comments