
Hey, what’s up, guys. In this post, we are going to learn about the DropdownButton widget in flutter. Let’s begin.
What does DropdownButton do in flutter?
We use DropdownButton to create a Dropdown list(Dropdown menu) in flutter. The DropdownButton widget shows a list of items when a user taps on it. Then the user can select any one item from the list.
Here’s what the documentation says –
“A material design button for selecting from a list of items.”
The purpose of the DropdownButton widget can also be achieved using the radio button. But, the problem is the number of items. If the number of items is less, then there’s no problem, but what if you have a large number of items to select from, like, a list of 100 colors. In this case, it’s better not to use the radio button. Use the DropdownButton widget for a better user experience.
Now, let’s see the code to create a Dropdown list in flutter.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'DropdownButton Example';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String dropdownValue = 'Bentley';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward, color: Colors.blue),
elevation: 16,
style: const TextStyle(color: Colors.blue),
underline: Container(
height: 2,
color: Colors.blue,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: <String>['Bentley', 'Porsche', 'Ferrari', 'BMW']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
Output:
Output before clicking the button.

Output after clicking the button:

And that ends the post here.
Goodbye.
Leave a Reply