The recommended method is using the HTML `<dialog>` element for its accessibility and native browser support.
Opens with a JS helper and closes natively thanks to a `Button` with `isNativeSubmit: true` inside a `<form method="dialog">`.
open modal
Hello!
Press ESC key or click the button below to close
import 'package:deepyr/deepyr.dart';
import 'package:jaspr/jaspr.dart';
import 'package:universal_web/web.dart' show HTMLDialogElement, document;
/// Helper to open the modal via JS interop.
void _showModal(String id) {
(document.getElementById(id) as HTMLDialogElement?)?.showModal();
}
class MyModalComponent extends StatelessComponent {
@override
Component build(BuildContext context) {
return Component.fragment([
// Button to trigger the modal
Button(
[text('open modal')],
onClick: (_) => _showModal('my_modal_1'),
),
// The Modal component
Modal(
[
ModalBox([
h3(classes: 'font-bold text-lg', [text('Hello!')]),
p(classes: 'py-4', [text('Press ESC key...')]),
ModalAction([
form(attributes: {'method': 'dialog'}, [
// This allows the form to close the dialog natively.
Button([text('Close')], isNativeSubmit: true),
]),
]),
]),
],
tag: 'dialog',
id: 'my_modal_1',
)
]);
}
}
Dialog modal that closes when clicked outside
A second `<form method="dialog">` with the `modal-backdrop` class is used. The button inside is required for it to function.
open modal
Hello!
Press ESC key or click outside to close
import 'package:deepyr/deepyr.dart';
import 'package:jaspr/jaspr.dart';
// ... (requires a trigger Button and _showModal helper)
Modal(
[
ModalBox([
h3(classes: 'font-bold text-lg', [text('Hello!')]),
p(classes: 'py-4', [text('Press ESC key or click outside to close')]),
]),
// The form itself is the backdrop. The button inside makes it functional.
form(
attributes: {'method': 'dialog'},
classes: 'modal-backdrop',
[button([text('close')])],
),
],
tag: 'dialog',
id: 'my_modal_2',
)
Dialog modal with custom width
Apply `deepyr` `Size` utilities directly to the `ModalBox`'s `style` property.
open modal
Hello!
Click the button below to close
import 'package:deepyr/deepyr.dart';
import 'package:jaspr/jaspr.dart';
// ... (requires a trigger Button and _showModal helper)
Modal(
[
ModalBox(
[
h3(classes: 'font-bold text-lg', [text('Hello!')]),
p(classes: 'py-4', [text('Click the button below to close')]),
ModalAction([
form(attributes: {'method': 'dialog'}, [
Button([text('Close')], isNativeSubmit: true),
]),
]),
],
style: [Size.w11_12, Size.maxW5xl],
),
],
tag: 'dialog',
id: 'my_modal_4',
)
Use the `.at(Breakpoint)` fluent API on `Modal` placement modifiers to change its position based on screen size.