I am new to Dart and I wonder if I can, for example, extend the DivElement class to create custom elements in one line of code. I am looking for something like this;
class RedBox extends DivElement {
RedBox(text) {
this.text = text;
this.style.background = "red";
}
}
RedBox myBox = new RedBox("Hello World");
document.body.append(myBox);
Of course I will have much more complex elements with custom functions. But just in general, is this possible?
When I try to run this, i get:
implicit call to super constructor 'DivElement()'
You can extend HTML elements, but there are a few requirements. The one you're running into now is that you need a RedBox.created
constructor, and it can only redirect to its super class. created
must be the only generative constructor, though you can add factory constructors.
Another requirement is that the element is registered with document.registerElement.
Try adding this:
class RedBox extends HtmlElement {
RedBox.created() : super.created() {
style.background = "red";
}
factory RedBox(text) => new Element.tag('my-redbox')..text = text;
}
document.registerElement('my-redbox', RedBox);
Some note on extending HtmlElement.
Example:
https://api.dartlang.org/1.14.1/dart-html/HtmlDocument/registerElement.html
Pitfalls:
HierarchyRequestError: Custom element XXX is a native PreElement should be derived from HtmlElement or SvgElement.
document.registerElement('xxx', XXX, extendsTag:'pre');
Solution(Assuming extending PreElement):
Use 'document.registerElement('xxx', XXX, extendsTag:'pre');' and 'new Element.tag('pre','xxx');'
void main{
document.registerElement('xxx',
XXX,extendsTag: 'pre');
querySelectior('body').append(new XXX()..text = 'hello');
}
class XXX extends PreElement{
XXX.created():super.created(){}
factory XXX(){
return new Element.tag('pre','xxx');
}
}
Dart does not currently support library initialization. You must call document.registerElement in the main.
Tested with 1.14.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With