Display Alert Dialog in Flutter

Display Alert Dialog in Flutter

An alert dialog is a popup window that is displayed in front of the current content. It informs a user about important information or asks to make a decision and take a action. An alert dialog can have title, content and a list of action buttons.

The AlertDialog class allows to create an alert dialog. We can display it using showDialog() function.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  _showDialog(BuildContext context) {
    AlertDialog alert = AlertDialog(
      title: const Text('My title'),
      content: const Text('My message'),
      actions: [
        ElevatedButton(
          child: const Text('OK'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ],
    );

    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Alert dialog')),
        body: Center(
            child: ElevatedButton(
          child: const Text('Open'),
          onPressed: () => _showDialog(context),
        )));
  }
}

Leave a Comment

Cancel reply

Your email address will not be published.