Display Dropdown Button in Flutter

Display Dropdown Button in Flutter

A dropdown button displays a list of items when it was clicked and lets the user select one of them.

A DropdownButton class can be used to create a dropdown button. The items property contains the list of items the user can select. The onChanged callback is called when the user selects the item from a list. The value property holds currently selected item.

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _selectedItem = 'Yellow';
  final List<String> _items = ['Yellow', 'Green', 'Red', 'Blue'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Dropdown button')),
        body: Center(
            child: DropdownButton(
          value: _selectedItem,
          items: _items.map((item) {
            return DropdownMenuItem(
              value: item,
              child: Text(item),
            );
          }).toList(),
          onChanged: (value) {
            setState(() {
              _selectedItem = value!;
            });
          },
        )));
  }
}

Leave a Comment

Cancel reply

Your email address will not be published.