You are currently viewing Flutter AlertDialog Tutorial and Examples

Flutter AlertDialog Tutorial and Examples

In this tutorial we will look at options for creating alert dialog in flutter. This involves creating them with or without third party packages.

What is an alert dialoG?

An alert dialog informs the user about situations that require acknowledgement.

What is Flutter?

Flutter is Google’s mobile app SDK for crafting high-quality native interfaces on iOS and Android in record time.

Flutter works with existing code, is used by developers and organizations around the world, and is free and open source.

Example 1: Flutter Simple AlertDialog Example

Let's look at a simple flutter alertdialog example with title and descriptions. In this example first we render a flat button that when the user presses or clicks, we open an alert dialog. In this example we do not use any third party library.

Here's the app in landscape mode:

Video tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel. Basically we have a TV for programming where do daily tutorials especially android.

Here are the files we explore:

  1. pubspec.yaml
  2. lib/main.dart

Step 1: Dependencies

Flutter supports using shared packages contributed by other developers to the Flutter and Dart ecosystems. This allows you to quickly build your app without having to develop everything from scratch.

We will be adding packages under this file.

  1. Open the pubspec.yaml file located inside your app folder, and add dependencies under dependencies.
  2. If it is a third party then you have to install it.
    From the terminal: Run flutter packages get

OR

From Android Studio/IntelliJ: Click 'Packages Get' in the action ribbon at the top of pubspec.yaml
From VS Code: Click 'Get Packages' located in right side of the action ribbon at the top of pubspec.yaml

flutter is always our sdk dependency as we use it to develop our ios and android apps.

name: mr_alert_dialog
description: A new Flutter project.
dependencies:
  flutter:
    sdk: flutter
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
dev_dependencies:
  flutter_test:
    sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

As you can see we've used the standard packages and no third party library.

Step 2: Write Code

main.dart is where we write our flutter code in dart programming language. In Dart it is very common to write several classes in a single file. So this simple file will have three classes.

1. How to Packages in Flutter/Dart
But first we need to import some packages and we do that using the import keyword in dart.

import 'package:flutter/material.dart';

Here are the packages we are importing:

  1. material.dart : will give us material design widgets and theme.

2. How to classes in Flutter/Dart
In Dart like in most C style programming languages you create a class using the class keyword. Classes are encapsulation mechanism in Object Oriented Programming languages.

In this case we create three classes:
1.class MyApp extends StatelessWidget {..}

  1. class Home extends StatefulWidget {..}

Our first class is deriving from StatelessWidget and implementing the build() method. That method will build a MaterialApp widget with title, home and theme set and return it as a widget.

The second class will derive from StatefulWidget and override the createState() method.

Here's the full source code:

import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter AlertDialog',
      home: Scaffold(
        appBar: AppBar(
          title: Text("AlertDialog Example"),
        ),
        body: Home(),
      ),
      theme: new ThemeData(primaryColor: Colors.orange),
    );
  }
}
class Home extends StatelessWidget {
  /**
  Comstruct our widget and return it.
   */
  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        onPressed: () {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              // return object of type AlertDialog
              return AlertDialog(
                title: new Text("AlertDialog Class"),
                content: new Text("Creates an alert dialog.Typically used in conjunction with showDialog."+
                "The contentPadding must not be null. The titlePadding defaults to null, which implies a default."),
                actions: <Widget>[
                  // usually buttons at the bottom of the dialog
                  new FlatButton(
                    child: new Text("Close"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        },
        child: Text('Show AlertDialog'),
      ),
    );
  }
}
void main() {
  runApp(new MyApp());
}
//end

Running Flutter Applications

Just make sure you device or emulator is running and click the run button in android studio, it will automatically pick the device and install the app.

Aletrnative you can use the terminal or command prompt. Navigate/Cd over to project root page and type this:

flutter.bat build apk

This will build the APK which you can then drag and install onto your device. The build process in my machine takes around three minutes which is not bad.

Example 2: Flutter Confirmation Dialog

import 'package:flutter/material.dart';
void main(){ runApp(new MaterialApp(
  home: new MyApp(),
));
}
enum MyDialogueAction{
  yes,
  no,
  maybe
}
class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
  String _text = '';
  void _onChange(String value) {
    setState((){
      _text = value;
    });
  }
  void _dialogueResult(MyDialogueAction value){
    print('you selected $value');
    Navigator.pop(context);
  }
 void _showAlert(String value){
  showDialog(
    context: context,
    builder: (_) => new AlertDialog(
      title: new Text('Alert!'),
      content: new Text(value,
      style: new TextStyle(fontSize: 30.0),),
      actions: <Widget>[
        new FlatButton(onPressed: () {_dialogueResult(MyDialogueAction.yes);}, child: new Text('yes')),
        new FlatButton(onPressed: () {_dialogueResult(MyDialogueAction.no);}, child: new Text('no')),
      ],
    )
  );
}
  @override
  Widget build (BuildContext context){
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Alert Demo'),
      ),body: new Container(
        child: new Column(
          children: <Widget>[
            new TextField(onChanged: (String value){ _onChange(value);},),
            new RaisedButton(
              onPressed: (){_showAlert(_text);},
              child: new Text('Press me'),
            )
          ],
        ),
      ),
    );
  }
}

Example 3: Animated, Giffy Dialog Example

If you want to have some more with your alert dialogs then you need to use third party packages such as this one.

Giffy Dialog is a beautiful and custom alert dialog for flutter highly inspired from FancyAlertDialog-Android.

The source code is 100% Dart, and everything resides in the /lib folder.

Through this solution you can load gif image dialog headers locally or remotely from the network.

Here is a demo of this dialog in use:

Network

Step 1: Install it

In your pubspec.yaml add this package as a dependency:

dependencies:
  giffy_dialog: 1.8.0

flutter pub get to fetch it.

Step 2: Prepare Images

Add some images in the assets folder or prepare image urls.

Step 3: Write Code

Start by importing giffy_dialog:

import 'package:giffy_dialog/giffy_dialog.dart';

Here is how you create a dialog with a header image loaded from the network:

onPressed: () {
  showDialog(
  context: context,builder: (_) => NetworkGiffyDialog(
    imageUrl:"https://raw.githubusercontent.com/Shashank02051997/
              FancyGifDialog-Android/master/GIF's/gif14.gif",
    title: Text('Granny Eating Chocolate',
            textAlign: TextAlign.center,
            style: TextStyle(
            fontSize: 22.0,
            fontWeight: FontWeight.w600)),
    description:Text('This is a granny eating chocolate dialog box.
          This library helps you easily create fancy giffy dialog',
          textAlign: TextAlign.center,
        ),
    entryAnimation: EntryAnimation.BOTTOM_TOP,
    onOkButtonPressed: () {},
  ) );
}

And here is how you create a dialog with header image loaded from assets folder:

onPressed: () {
  showDialog(
  context: context,builder: (_) => AssetGiffyDialog(
    imagePath: 'assets/men_wearing_jacket.gif',
    title: Text('Men Wearing Jackets',
            style: TextStyle(
            fontSize: 22.0, fontWeight: FontWeight.w600),
    ),
    description: Text('This is a men wearing jackets dialog box.
          This library helps you easily create fancy giffy dialog.',
          textAlign: TextAlign.center,
          style: TextStyle(),
        ),
    entryAnimation: EntryAnimation.RIGHT_LEFT,
    onOkButtonPressed: () {},
  ) );
}

Asset

Full Example

Start by installing the library as has been discussed above.

Then replace your main.dart with the following code:

main.dart

import 'package:flutter/material.dart';
import 'package:giffy_dialog/giffy_dialog.dart';
void main() => runApp(new MyApp());
const List<Key> keys = [
  Key("Network"),
  Key("NetworkDialog"),
  Key("Flare"),
  Key("FlareDialog"),
  Key("Asset"),
  Key("AssetDialog")
];
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Giffy Dialog Demo',
      theme: ThemeData(primarySwatch: Colors.teal, fontFamily: 'Nunito'),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Giffy Dialog Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
                key: keys[0],
                color: Colors.teal,
                child: Text(
                  "Network Giffy",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  showDialog(
                      context: context,
                      builder: (_) => NetworkGiffyDialog(
                            key: keys[1],
                            image: Image.network(
                              "https://raw.githubusercontent.com/Shashank02051997/FancyGifDialog-Android/master/GIF's/gif14.gif",
                              fit: BoxFit.cover,
                            ),
                            entryAnimation: EntryAnimation.TOP_LEFT,
                            title: Text(
                              'Granny Eating Chocolate',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 22.0, fontWeight: FontWeight.w600),
                            ),
                            description: Text(
                              'This is a granny eating chocolate dialog box. This library helps you easily create fancy giffy dialog.',
                              textAlign: TextAlign.center,
                            ),
                            onOkButtonPressed: () {},
                          ));
                }),
            RaisedButton(
                key: keys[2],
                color: Colors.teal,
                child: Text(
                  'Flare Giffy',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  showDialog(
                      context: context,
                      builder: (_) => FlareGiffyDialog(
                            key: keys[3],
                            flarePath: 'assets/space_demo.flr',
                            flareAnimation: 'loading',
                            title: Text(
                              'Space Reloading',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 22.0, fontWeight: FontWeight.w600),
                            ),
                            entryAnimation: EntryAnimation.DEFAULT,
                            description: Text(
                              'This is a space reloading dialog box. This library helps you easily create fancy flare dialog.',
                              textAlign: TextAlign.center,
                              style: TextStyle(),
                            ),
                            onOkButtonPressed: () {},
                          ));
                }),
            RaisedButton(
                key: keys[4],
                color: Colors.teal,
                child: Text(
                  'Asset Giffy',
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                onPressed: () {
                  showDialog(
                      context: context,
                      builder: (_) => AssetGiffyDialog(
                            key: keys[5],
                            image: Image.asset(
                              'assets/men_wearing_jacket.gif',
                              fit: BoxFit.cover,
                            ),
                            title: Text(
                              'Men Wearing Jackets',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: 22.0, fontWeight: FontWeight.w600),
                            ),
                            entryAnimation: EntryAnimation.BOTTOM_RIGHT,
                            description: Text(
                              'This is a men wearing jackets dialog box. This library helps you easily create fancy giffy dialog.',
                              textAlign: TextAlign.center,
                              style: TextStyle(),
                            ),
                            onOkButtonPressed: () {},
                          ));
                }),
          ],
        ),
      ),
    );
  }
}

Reference

Here are the reference links:

Number Link
1. Download example
2. Read more
3. Follow code author

Leave a Reply