Sunday, February 12, 2012

Modal dialog in Dart…

Modal dialog in Dart…

There was a post on the dart mailing list ^ about how to do a modal dialog in dart.
As I’m in the middle of writing an app that has a modal dialog, I’ve pulled out the relevant bits of code and stuck them here, in the hope that they will be of use.
The CSS is copy of something that I googled – a Javascript + CSS lightbox type solution, so credit where it’s due:^
The basic idea is that when someone clicks a button, we first put a full screen dark overlay over the UI, then on top of that, in the center, we put another Div containing a message, and a button which clears that div.
Modal dialog
Here’s the CSS:
 display: block;
 position: absolute;
 top: 0%;
 left: 0%;
 width: 100%;
 height: 100%;
 background-color: black;
 -moz-opacity: 0.8;
 filter: alpha(opacity=80);

.white_content {
 display: block;
 position: absolute;
 top: 25%;
 left: 25%;
 width: 50%;
 height: 50%;
 padding: 16px;
 border: 16px solid orange;
 background-color: white;
 overflow: auto;
And here’s the Dart:


void main() {
  //setup the screen elements...
  ButtonElement button = new Element.tag("button");
  button.text = "click me";
  //add an event handler {
    ModalDialog dialog = new ModalDialog("This is a <strong>message</strong>
with html formatting");;
  //add the button to the screen

  //add the modal dialog stylesheet


* Our modal dialog class
class ModalDialog {
  final DivElement _content;
  final DivElement _blackOverlay;
  final ButtonElement _button;

  ModalDialog(String message) :
    //constructor pre-init
    _content = new Element.tag("div"),
    _blackOverlay = new Element.tag("div"),
    _button = new Element.tag("button")
    //constructor body = "modalContent";
    _content.classes.add("white_content");  //set the class for CSS = "modalOverlay";
    _blackOverlay.classes.add("black_overlay"); //set the class for CSS

    //Our message will go inside this span
    SpanElement span = new Element.tag("span");
    span.innerHTML = message;

    //This is the button that will "clear" the dialog
    _button.text = "Ok"; {


  //remove the modal dialog div's from the dom.
  hide() {
    //find the element and remove it.
    //there is no list.remove(x) statement at present,
    // so we have to do it manually.
    removeFromList(_content, document.body.nodes);
    removeFromList(_blackOverlay, document.body.nodes);

  //add the modal dialog div's to the dom
  show() {


* Utility method to get a stylesheet object
getStylesheet() {
  LinkElement styleSheet = new Element.tag("link");
  styleSheet.rel = "stylesheet";
  return styleSheet;

*  Quick and dirty
*  Remove the item from the list
removeFromList(var item, var list) {
  int indexToRemove = 0;
  for (int i = 0; i < list.length; i++) {
    var element = list[i];
    if (element == item) {
      indexToRemove = i;



No comments:

Post a Comment