DropdownButton widget is used to create a dropdown menu. A dropdown menu allows users to select a single item from a list of options.
There Are Some Common Attributes for DropdownButton
value | value property represents the current state of the DropdownButton |
onChanged | The onChanged callback is triggered when the DropdownButton change value. |
Here's a simple example of using a DropdownButton in Flutter:
File open lib->main.dart file −
import 'package:flutter/material.dart';
void main() {
runApp(
MyApp()
);
}
class MyApp extends StatefulWidget{
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _selectedItem="Flutter";
// List of items for the dropdown
List<String> _items = ['Flutter', 'Java', 'Kotlin', 'JetPack'];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('DropdownButton Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
DropdownButton(
value: _selectedItem,
items: _items.map((String item) {
return DropdownMenuItem(
value: item,
child: Text(item),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedItem = value!;
});
},
),
SizedBox(height: 20),
Text('Selected Item: $_selectedItem'),
],
),
)
));
}
}
Open
Device Manager, run the emulator, and then run the application. Next,
check the working output and check the output you declared in your
code.
Output: