A Flutter/Dart AlertDialog example

As a brief note to self, here’s an example of how to create a popup dialog (AlertDialog) using Dart and Flutter:

import 'package:flutter/material.dart';
import 'package:todo_list/todo.dart';

class NewTodoDialog extends StatelessWidget {

    final controller = new TextEditingController();

    @override
    Widget build(BuildContext context) {
        return AlertDialog(
            title: Text('New Task'),
            content: TextField(
                controller: controller,
                autofocus: true,
            ),
            actions: <Widget>[
                FlatButton(
                    child: Text('Cancel'),
                    onPressed: () {
                        Navigator.of(context).pop();
                    },
                ),
                FlatButton(
                    child: Text('Add'),
                    onPressed: () {
                        final todo = new ToDo(title: controller.value.text);
                        controller.clear();
                        Navigator.of(context).pop(todo);
                    },
                ),
            ],
        );
    }
}

That code results in this AlertDialog on an iOS device:

A Flutter/Dart AlertDialog example

Most of that code is generic, so it shows a good example of how to create a Flutter AlertDialog.

The source code shown comes from this Github project: