FlatButton with Simple AlertDialog


import 'package:flutter/material.dart';

//this is the entry point
main() => runApp(MyMainPage());

//A StatelessWidget that does not require mutable state.
class MyMainPage extends StatelessWidget {
  //Describes the part of the user interface represented by this widget.
  @override
  Widget build(BuildContext context) {
    //Creates a MaterialApp widget.
    return MaterialApp(
      //Creates a visual scaffold for material design widgets.
      home: Scaffold(
        //An app bar to display at the top of the scaffold.
        appBar: AppBar(
          //The primary widget displayed in the app bar.
          title: Text("Title Here"),
        ),

        //The body is primary content of the scaffold.
        body: MyButton(),
      ),
    );
  }
}

//A StatefulWidget that has mutable state.
class MyButton extends StatefulWidget {
  //Creates the mutable state for this widget at a given location in the tree.
  @override
  MyButtonState createState() => MyButtonState();
}

//The logic and internal state for a [StatefulWidget].
class MyButtonState extends State {
  //Describes the part of the user interface represented by this widget.
  @override
  Widget build(BuildContext context) {
    //Create a simple text button.
    return FlatButton(
      //Creates a text widget with text color.
      child: Text(
        "Click Me",
        style: TextStyle(color: Colors.red),
      ),

      //It just like event task.
      onPressed: () {
        //call a custom method to display the alert.
        showMyDialog(context);
      },
    );
  }
//this is a custom method to show alert dialog
  showMyDialog(BuildContext context) {
// set up the alert dialog button
    Widget gotIt = FlatButton(
      //this is the name of button
      child: Text("Got It"),

      //this is the task of gotit button
      onPressed: () {
        //using Navigator.of we can dismiss an alert dialog.
        Navigator.of(context, rootNavigator: true).pop('alert');
      },
    );

    // set up the AlertDialog to be display when user click on button
    AlertDialog alert = AlertDialog(
      //this is the title of alert dialog
      title: Text("My title"),

      //this is the message of content of alert dialog
      content: Text("Welcome to Hello World."),

      //you can define number of button here.
      actions: [
        gotIt,
      ],
    );

    // display the dialog to screen and it is a built in function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}

No comments: