Skip to main content

Flutter Show Simple Alert Dialog

Alert Dialogs alerts the app user with a popup window on screen including a OK button. Main purpose of alert dialog is to interact with app user by showing him a visual popup screen telling him feedback of his event. In today's tutorial we will make simple alert dialog box same as alert() in react native.

Flutter Show Simple Alert Dialog

1. There are a predefine widget in flutter showDialog() to display material style alert dialog over screen. We have to call showDialog() in another function with Future ASYNC method. 
  Future<void> simpleAlert() async {
    await showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Simple Alert With OK Button.'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('OK'),
            )
          ],
        );
      },
    );
  }
2. Create a Button to open Alert Dialog.
ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.cyan,
          textStyle: const TextStyle(fontSize: 21),
        ),
        onPressed: simpleAlert,
        child: const Text('Show Alert'),
      ),
Screenshots:
Flutter Show Simple Alert Dialog


Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: MyApp()));
  }
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State {
  Future<void> simpleAlert() async {
    await showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Simple Alert With OK Button.'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('OK'),
            )
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.cyan,
          textStyle: const TextStyle(fontSize: 21),
        ),
        onPressed: simpleAlert,
        child: const Text('Show Alert'),
      ),
    );
  }
}

Comments