2.5 C
New York
Friday, December 2, 2022

Working with Dialog in Flutter

To show a dialog in Flutter, you can use the built-in showDialog() function and the Dialog widget.

Simple implementation:Advertisements

void _show(BuildContext ctx) {
    showDialog(
      context: ctx,
      builder: (context) {
        return Dialog(
          elevation: 6,
          insetPadding:
              const EdgeInsets.symmetric(vertical: 240, horizontal: 30),
          child: Center(
            child: TextButton(
              child: const Text('Close'),
              onPressed: () => Navigator.of(ctx).pop(),
            ),
          ),
        );
      },
    );
}

To close the dialog, just use (the user can also close the dialog by tap somewhere outside it):

Navigator.of(ctx).pop()

The Complete Example

This example is a small Flutter app that contains a button in the center of the screen. When the user press this button, a dialog shows up. The dialog has a button that allows the user to close it.

Here’s how it works:

AdvertisementsFull source code in main.dart:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  void _show(BuildContext ctx) {
    showDialog(
      context: ctx,
      builder: (context) {
        return Dialog(
          elevation: 6,
          insetPadding:
              const EdgeInsets.symmetric(vertical: 240, horizontal: 30),
          child: Center(
            child: TextButton(
              child: const Text('Close'),
              onPressed: () => Navigator.of(ctx).pop(),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        child: GestureDetector(
            onTap: () {},
            child: Center(
              child: TextButton(
                child: const Text('Show the Dialog'),
                onPressed: () {
                  _show(context);
                },
              ),
            )),
      ),
    );
  }
}

You’ve learned how to implement the simplest Dialog in Flutter. Continue exploring more about dialog things and other interesting stuff in Flutter by taking a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles