Skip to content

Instantly share code, notes, and snippets.

@mhadaily
Last active January 18, 2022 00:48
Show Gist options
  • Save mhadaily/2be8db23e4139bd8d75d93270ad1b8a7 to your computer and use it in GitHub Desktop.
Save mhadaily/2be8db23e4139bd8d75d93270ad1b8a7 to your computer and use it in GitHub Desktop.
Adding custom DOM elements using HTML slots to render platform views in the Flutter web
<script>
document.querySelector('#username').addEventListener('input', console.log);
document.querySelector('#password').addEventListener('input', console.log);
</script>
import 'package:flutter/material.dart';
import 'dart:html' as dom;
import 'dart:ui' as ui;
void main() {
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'username',
(int viewId) => dom.Element.html(
'<input type="text" id="username" name="password" placeholder="Username">',
validator: dom.NodeValidatorBuilder()..allowHtml5(),
)
// ..addEventListener('input', (event) => print(event.target))
..style.width = '100%'
..style.height = '100%',
);
// ignore: undefined_prefixed_name
ui.platformViewRegistry.registerViewFactory(
'password',
(int viewId) => dom.Element.html(
'<input type="password" id="password" name="password" placeholder="Password">',
validator: dom.NodeValidatorBuilder()..allowHtml5(),
)
// ..addEventListener('input', (event) => print(event.target))
..style.width = '100%'
..style.height = '100%',
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Web Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Padding(
padding: EdgeInsets.all(25),
child: SizedBox(
width: 640,
height: 60,
child: HtmlElementView(viewType: 'username'),
),
),
Padding(
padding: EdgeInsets.all(25),
child: SizedBox(
width: 640,
height: 60,
child: HtmlElementView(viewType: 'password'),
),
),
],
),
),
);
}
}
/// Now you can listen to any input changes from the two input you have added to the Flutter web via Javascirpt in index.html or maybe you can use a JS library too.
// then build for web, you need to make sure you have flutter stable greater than 2.5
// flutter build web
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment