To create a reusable DropdownSearch widget using the dropdown_search package in Flutter, you can follow these steps:
- Import the dropdown_search package in your Flutter project by adding it to your dependencies in the pubspec.yaml file:
dependencies:
dropdown_search: ^latest_version
-
Create a new file for your dropdown_search widget (e.g., dropdown_widget.dart).
-
In the dropdown_widget.dart file, import the necessary packages:
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
- Create a stateful widget class for your dropdown widget:
class DropdownWidget extends StatefulWidget {
@override
_DropdownWidgetState createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String selectedItem;
@override
Widget build(BuildContext context) {
return DropdownSearch<String>(
items: ["Item 1", "Item 2", "Item 3"],
selectedItem: selectedItem,
hint: "Select an item",
onChanged: (value) {
setState(() {
selectedItem = value;
});
},
);
}
}
- In the build method of your widget tree, you can now use your DropdownWidget:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Example'),
),
body: Center(
child: DropdownWidget(),
),
);
}
- To get the selected item from the DropdownSearch widget in another part of your app, you can add a callback function to the DropdownWidget class:
class DropdownWidget extends StatefulWidget {
final Function(String) onItemSelected;
DropdownWidget({Key key, this.onItemSelected}) : super(key: key);
@override
_DropdownWidgetState createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String selectedItem;
@override
Widget build(BuildContext context) {
return DropdownSearch<String>(
items: ["Item 1", "Item 2", "Item 3"],
selectedItem: selectedItem,
hint: "Select an item",
onChanged: (value) {
setState(() {
selectedItem = value;
});
widget.onItemSelected(value); // Callback function
},
);
}
}
- In the parent widget where you use the DropdownWidget, you can pass a callback function to handle the selected item:
DropdownWidget(
onItemSelected: (value) {
// Do something with the selected item
print(value);
},
),
Now, whenever the user selects an item from the DropdownSearch widget, the selected item will be passed to the callback function provided and you can handle it as per your requirement.