How to create HTML Web Components with Dart
I am a long time Web Components fan (since helping DevRel lit.dev and Material Web Components) and have also loved writing Dart in both Flutter applications and full stack apps.
Despite being used at so many companies, Web Components have faced a lot of pushback from JavaScript developers that use frameworks to target the web. ☹️
What you may not realize is that the web has a way to create new HTML tags that can be used in ANY JS framework or place that returns HTML and you can progressively enchance applications. 🤩
Since they are custom HTML tags, if you swap implementations, you do not need to update where it is used and you can ship components a separate files instead of one big bundle.
Dart used to support Web Components at one point and was even used by a precursor to Lit in a product call Polymer.
Creating a Web Component in Javascript
To create a web component in Javascript you just need to extend HTML element and provide callbacks for when the component is mounted.
class HelloWorld extends HTMLElement {
static observedAttributes = ["name"];
constructor() {
super();
}
update() {
this.innerHTML = `Hello: ${this.getAttribute('name')}`;
}
connectedCallback() {
console.log("Custom element added to page.");
this. update();
}
disconnectedCallback() {
console.log("Custom element removed from page.");
}
adoptedCallback() {
console.log("Custom element moved to new page.");
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} has changed.`);
if (name === 'name') {
this. update();
}
}
}
customElements.define("hello-world", HelloWorld);
We can then use it in HTML like the following:
<html>
<body>
<hello-world name="Rody"></hello-world>
<script src="./index.js"></script>
</body>
</html>
This works really well, and we don't even need a build step to create them!
Creating Web Components with Dart
To create them on the Dart side we need to use the js\_interop package and the new web package.
We need to create a factory on the dart side that can create these JS classes without actually being able to create a class in the normal way (since JS and Dart classes are different).