DEV Community

Aadarsh Kunwar
Aadarsh Kunwar

Posted on

Flutter DropdownButton

The DropdownButton widget in Flutter is a convenient way to create a dropdown menu that allows users to select from a list of options. It displays the currently selected item and provides a menu for selecting another item when tapped.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Dropdown Button Example')),
        body: Center(child: DropdownButtonExample()),
      ),
    );
  }
}

class DropdownButtonExample extends StatefulWidget {
  @override
  _DropdownButtonExampleState createState() => _DropdownButtonExampleState();
}

class _DropdownButtonExampleState extends State<DropdownButtonExample> {
  String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: selectedValue,
      hint: Text('Select an option'),
      items: <String>['Option 1', 'Option 2', 'Option 3']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (String? newValue) {
        setState(() {
          selectedValue = newValue;
        });
      },
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Key Properties of DropdownButton

  • value: The currently selected item. If it is null, the dropdown will show the hint.
  • hint: A widget that is displayed when no item is selected.
  • items: A list of DropdownMenuItem widgets that represent the options in the dropdown.
  • onChanged: A callback that is called when the user selects an item from the dropdown. It receives the new value as a parameter.

Top comments (0)