How to show a Dialog Box on a Button Click in Flutter?

This Article is posted by seven.srikanth at 29-09-2018 04:16:27

In this post, I'm going to show you how to show a Dialog box on a Button Click.
The final output is going to look like below. On button click, you will see the Dialog box shown below.
Here is the final code from Main.dart file. All you need to do it copy to the main.dart file on your newly created flutter project.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _showcontent() {
showDialog<Null>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return new AlertDialog(
title: new Text('You clicked on'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text('This is a Dialog Box. Click OK to Close.'),
],
),
),
actions: <Widget>[
new FlatButton(
child: new Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'Push the button to show a Dialog:',
),
new RaisedButton(onPressed: _showcontent, color: Colors.blueAccent,
child:
new Text('Click here', style: TextStyle(color: Colors.white)),
),
],
),
),
);
}
}
Let me know if this helps through your comments.
Thanks,
Srikanth

Tags: show a Dialog Box on a Button Click; Popup Dialog Box; Button Click Event; Coloring Button; AlertDialog Widget;



1 Comments
Login to comment.
Recent Comments

ice.simx at 19-06-2019

Code Correction; instead of ShowDialog<Null> it should be ShowDialog<void> https://api.flutter.dev/flutter/material/AlertDialog-class.html

Login to Reply.




Recent Articles


How to deploy flutter web site on GitHub using peanut

Posted by nikhilchaudhary12155 on 13 Oct 2019 Article


AnimatedPositioned Widget Example in Flutter

Posted by seven.srikanth on 10 Oct 2019 Article


Flutter Open-Source and directory lists

Posted by nishantkotatech on 09 Oct 2019 Article


Flutter Travelling Couple Leading Page - Flutter Web Series 3

Posted by nikhilchaudhary12155 on 05 Oct 2019 Article



© 2018 - Fluttercentral | Email to me - Seven.srikanth@gmail.com