Flutter, Google's UI toolkit for building natively compiled applications, provides a versatile set of widgets to create intuitive and interactive user interfaces. One such widget is the DropdownButton, commonly used to implement dropdown menus. In this article, we'll explore the DropdownMenu widget in Flutter, its key attributes, and provide a hands-on example.
In Flutter, there isn't a specific "DropdownMenu" widget; instead, we commonly use the DropdownButton widget. This widget is essential for scenarios where users need to select one option from a list.
Key Attributes of DropdownButton
value
The value attribute represents the currently selected option in the dropdown. It is crucial for maintaining the state of the selected item.
onChanged
The onChanged attribute is a callback function triggered when the user selects a different option. It allows you to handle the logic associated with the selection change.
items
The items attribute is a list of items in the dropdown, usually represented by DropdownMenuItem widgets. Each DropdownMenuItem corresponds to an option in the dropdown.
Now, let's delve into a practical example to demonstrate the usage of DropdownButton.
Example
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String selectedOption = 'None';
@override
Widget build(BuildContext context) {
Color backgroundColor;
// Update the background color based on the selected option
switch (selectedOption) {
case 'Option 1':
backgroundColor = Colors.red;
break;
case 'Option 2':
backgroundColor = Colors.blue;
break;
case 'Option 3':
backgroundColor = Colors.green;
break;
default:
backgroundColor = Colors.white;
}
return Scaffold(
appBar: AppBar(
title: Text('DropdownMenu Example'),
),
body: Container(
color: backgroundColor, // Set the background color
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DropdownButton<String>(
value: selectedOption,
onChanged: (String? newValue) {
setState(() {
selectedOption = newValue!;
});
},
items: <String>['None', 'Option 1', 'Option 2', 'Option 3']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
],
),
),
),
);
}
}
In this example:
The dropdown displays three options: 'Option 1', 'Option 2', and 'Option 3'.
The value and onChanged attributes handle the selected option's state and changes, respectively.