How to create a Dropdown widget to apply for any kinds of Lists in Flutter?
In this article, we’ll see how to create a dropdown widget and use it in multiple kinds of datasets.
Now let’s create a stateless class named as CustomDropdown:
import 'package:flutter/material.dart';
class CustomDropdown extends StatelessWidget {
const CustomDropdown({
Key? key,
this.label,
required this.value,
required this.dataList,
required this.onChanged,
}) : super(key: key);
final String? label;
final String value;
final List<DropdownMenuItem> dataList;
final Function onChanged;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (label != null)
Padding(
padding: const EdgeInsets.only(bottom: 8.0, left: 5.0),
child: Text(label!, style: lightStyle),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey.shade300,
),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: DropdownButtonHideUnderline(
child: DropdownButton(
icon: Icon(Icons.add),
iconSize: 25,
itemHeight: 57,
value: value,
style: normalStyle,
items: dataList,
onChanged: (val) {
onChanged(val);
},
),
),
),
),
],
);
}
}
Usage with key-value pair:
String customerId = "";
List customerList = [
{
"id": "1",
"name": "Dipen Maharjan"
},
{
"id": "2",
"name": "Slimpotatoboy"
},
];
Widget build(BuildContext context){
return Column(
children:[
if (customerList.isNotEmpty)
CustomDropdown(
value: customerId,
dataList: customerList.map<DropdownMenuItem>(
(item) {
return DropdownMenuItem(
value: item['id'],
child: Text(item['name']),
);
},
).toList(),
onChanged: (value){
setState(() {
customerId = value;
});
}
),
],
);
}
Usage with List of Strings:
// default selected show
String selectedPayment = "Credit Card";
List paymentList = ["Credit Card", "FonePay", "Wallet"];
Widget build(BuildContext context){
return Column(
children:[
if (paymentList.isNotEmpty)
CustomDropdown(
value: selectedPayment,
dataList: paymentList.map<DropdownMenuItem>(
(item) {
return DropdownMenuItem(
value: item,
child: Text(item),
);
},
).toList(),
onChanged: (value){
setState(() {
selectedPayment = value;
});
}
),
],
);
}
Conclusion
In this article, I have explained How you can use Dropdown Widget With Multiple datasets. You can change the data as per your need. If you need any help or confusion You can reach me out here: https://topmate.io/dipen
I hope this blog post provides you with enough information on Dropdown Widget for your projects.
Thank you for reading this article!
If you love the article, Clap 👏
Also follow me for more exciting articles related to dart and flutter.
If you found something wrong in the article, let me know! I would love to improve.
Let’s Get Connected
Find me on:
- Twitter
- IndiePage
- Youtube: @thefluttershow
- Github
- Linkedin
Support me: BuyMeACoffee
Consulation or 1:1 Flutter Mentorship : TopMate