0
0
Fluttermobile~5 mins

DropdownButton in Flutter

Choose your learning style9 modes available
Introduction

A DropdownButton lets users pick one option from a list. It saves space and keeps the screen tidy.

Choosing a country from a list when signing up.
Selecting a payment method during checkout.
Picking a color theme in app settings.
Choosing a language preference in a profile.
Syntax
Flutter
DropdownButton<T>(
  value: selectedValue,
  items: <DropdownMenuItem<T>>[
    DropdownMenuItem<T>(value: value1, child: Text('Option 1')),
    DropdownMenuItem<T>(value: value2, child: Text('Option 2')),
  ],
  onChanged: (T? newValue) {
    // update selectedValue
  },
)

T is the type of the values you want to select (like String or int).

You must provide items and onChanged to make it work.

Examples
A simple dropdown with fruit names as options.
Flutter
DropdownButton<String>(
  value: 'apple',
  items: [
    DropdownMenuItem(value: 'apple', child: Text('Apple')),
    DropdownMenuItem(value: 'banana', child: Text('Banana')),
  ],
  onChanged: (String? newValue) {
    // handle change
  },
)
Dropdown with numbers as options.
Flutter
DropdownButton<int>(
  value: 1,
  items: [
    DropdownMenuItem(value: 1, child: Text('One')),
    DropdownMenuItem(value: 2, child: Text('Two')),
  ],
  onChanged: (int? newValue) {
    // handle change
  },
)
Sample App

This app shows a dropdown with three fruits. When you pick one, it updates the selected fruit.

Flutter
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: FruitDropdown(),
        ),
      ),
    );
  }
}

class FruitDropdown extends StatefulWidget {
  const FruitDropdown({super.key});

  @override
  State<FruitDropdown> createState() => _FruitDropdownState();
}

class _FruitDropdownState extends State<FruitDropdown> {
  String selectedFruit = 'apple';

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: selectedFruit,
      items: const [
        DropdownMenuItem(value: 'apple', child: Text('Apple')),
        DropdownMenuItem(value: 'banana', child: Text('Banana')),
        DropdownMenuItem(value: 'orange', child: Text('Orange')),
      ],
      onChanged: (String? newValue) {
        if (newValue != null) {
          setState(() {
            selectedFruit = newValue;
          });
        }
      },
    );
  }
}
OutputSuccess
Important Notes

Always provide a value that matches one of the items values.

If onChanged is null, the dropdown is disabled.

Use setState to update the selected value inside a StatefulWidget.

Summary

DropdownButton lets users pick one choice from a list.

You must provide items, value, and onChanged.

Use inside a StatefulWidget to update the selected value dynamically.