How to Show Alert Dialog in your Flutter App

Showing alerts for users is an important aspect of a mobile app user interface. In this blog post, I am sharing a Flutter Alert Dialog example with you.

Alert Dialog is a material design widget which informs the user about some scenarios which need acknowledgment. We can show an optional title and optional actions with it.

In this flutter example, the alert dialog appears when the raised button is pressed. Here’s my main.dart file:

import 'package:flutter/material.dart';

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

//Function which shows Alert Dialog
  alertDialog(BuildContext context) {
  // This is the ok button
  Widget ok = FlatButton(
    child: Text("Okay"),
    onPressed: () {Navigator.of(context).pop();},
  ); 
  // show the alert dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
    return AlertDialog(
    title: Text("I am Here!"),
    content: Text("I appeared because you pressed the button!"),
    actions: [
      ok,
    ],
    elevation: 5,
    
  );
    },
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Alert Dialog Example'),
        ),
        //calling MyBody class
        body: MyBody(),
      ),
    );
  }
}

class MyBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
          child: 
         RaisedButton(
           //alertDialog function is called when button is pressed
            onPressed: () {alertDialog(context);},
            child: const Text('Click to show Alert!', style: TextStyle(fontSize: 20)),
            color: Colors.blue,
            textColor: Colors.white,
            elevation: 5,
          )
        );
  }
}

Following is the output of Flutter Alert Dialog example:

Have any doubts? let me know through the comment section below.

Leave a Comment

Your email address will not be published. Required fields are marked *