Open In App

Flutter – Implement DropdownButton Inside an AlertDialog

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

DropdownButton widget is used to create a dropdown menu that allows users to select one option from a list of available choices. It’s a common user interface element for selecting items from a list. An Alert Dialog is a useful way to grab users’ attention. Here we can see how to implement an AlertDialog, and then we are going to implement a DropdownButton inside the AlertDialog. In this article, we will implement the AertDialog and DropdownButton, A sample video is given below to get an idea about what we are going to do in this article.

Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




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


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      home: DropDownAlertDialog(),
    );
  }
}


Step 5: Create DropDownAlertDialog Class

In this class we are going to Implement the DropdownButton widget inside an Alert Dialog that help to create a dropdown menu where users can select one option from a list of available options and the selected option is displayed in the debug console window .Comments are added for better understanding.

 // Method for implementing an DropDownButton inside an AlertDialog
  void showMyDialog(BuildContext context) {
    // Creating an Dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
// Use a nullable type String? selectedItem = 'Option 1'; // Creating a list of avaliable options List<String> items = ['Option 1', 'Option 2', 'Option 3', 'Option 4']; return AlertDialog( title: Text('Select an option'), content: Column( mainAxisSize: MainAxisSize.min, children: [ DropdownButton<String>( value: selectedItem, items: items.map((String item) { return DropdownMenuItem<String>( value: item, child: Text(item), ); }).toList(), onChanged: (String? newValue) { // Use a nullable type for onChanged if (newValue != null) { selectedItem = newValue; } }, ), ], ), actions: [ ElevatedButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('Cancel'), ), ElevatedButton( onPressed: () { // Handle the selected item here if (selectedItem != null) { print('Selected item: $selectedItem'); } Navigator.of(context).pop(); }, child: Text('OK'), ), ], ); }, ); }

Dart




class DropDownAlertDialog extends StatelessWidget {
  const DropDownAlertDialog({super.key});
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dropdown in AlertDialog'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showMyDialog(context);
          },
          child: Text('Show AlertDialog'),
        ),
      ),
    );
  }
  //Method for implementing an DropDownButton inside an AlertDialog
  void showMyDialog(BuildContext context) {
    //Creating an Dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // Use a nullable type
        String? selectedItem = 'Option 1'
          
        // Creating a list of avaliable options
        List<String> items = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
  
        return AlertDialog(
          title: Text('Select an option'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              DropdownButton<String>(
                value: selectedItem,
                items: items.map((String item) {
                  return DropdownMenuItem<String>(
                    value: item,
                    child: Text(item),
                  );
                }).toList(),
                onChanged: (String? newValue) {
                  // Use a nullable type for onChanged
                  if (newValue != null) {
                    selectedItem = newValue;
                  }
                },
              ),
            ],
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Cancel'),
            ),
            ElevatedButton(
              onPressed: () {
                // Handle the selected item here
                if (selectedItem != null) {
                  print('Selected item: $selectedItem');
                }
                Navigator.of(context).pop();
              },
              child: Text('OK'),
            ),
          ],
        );
      },
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // Set the app's primary theme color
        primarySwatch: Colors.green, 
      ),
      home: DropDownAlertDialog(),
    );
  }
}
  
class DropDownAlertDialog extends StatelessWidget {
  const DropDownAlertDialog({super.key});
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dropdown in AlertDialog'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showMyDialog(context);
          },
          child: Text('Show AlertDialog'),
        ),
      ),
    );
  }
    
  // Method for implementing an 
  // DropDownButton inside an AlertDialog
  void showMyDialog(BuildContext context) {
    // Creating an Dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // Use a nullable type
        String? selectedItem = 'Option 1'
          
        // Creating a list of avaliable options
        List<String> items = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
        return AlertDialog(
          title: Text('Select an option'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              DropdownButton<String>(
                value: selectedItem,
                items: items.map((String item) {
                  return DropdownMenuItem<String>(
                    value: item,
                    child: Text(item),
                  );
                }).toList(),
                onChanged: (String? newValue) {
                  // Use a nullable type for onChanged
                  if (newValue != null) {
                    selectedItem = newValue;
                  }
                },
              ),
            ],
          ),
          actions: [
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Cancel'),
            ),
            ElevatedButton(
              onPressed: () {
                // Handle the selected item here
                if (selectedItem != null) {
                  print('Selected item: $selectedItem');
                }
                Navigator.of(context).pop();
              },
              child: Text('OK'),
            ),
          ],
        );
      },
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads