DEV Community

Aadarsh Kunwar
Aadarsh Kunwar

Posted on

1 1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay