Today we are going to create a custom widget called CustomDropdownButton
, which is used to display a DropdownButton with selectable options.
The widget accepts three parameters:
import 'package:flutter/material.dart'; import '../comun/Option.dart'; class CustomDropdownButton extends StatefulWidget { final Option selectedOption; final List options; final void Function(Option?) onChanged; CustomDropdownButton({ required this.selectedOption, required this.options, required this.onChanged, }); @override _CustomDropdownButtonState createState() => _CustomDropdownButtonState(); } class _CustomDropdownButtonState extends State { @override Widget build(BuildContext context) { return Expanded( child: DropdownButton( isExpanded: true, value: widget.selectedOption, onChanged: widget.onChanged, items: widget.options .map<DropdownMenuItem>( (option) => DropdownMenuItem( value: option, child: Text(option.name), ), ) .toList(), ), ); } }
selectedOption
: Represents the currently selected option in the dropdown menu.options
: Is a list of options to be displayed in the dropdown menu.onChanged
: Is a function that is called when the selection of the dropdown menu changes.
Widget Usage: To use this widget, simply incorporate it into the widget tree and provide the required parameters as shown below
CustomDropdownButton( selectedOption: mySelectedOption, options: optionsList, onChanged: (newOption) { // Logic to handle the change in the selected option. // You can update the state or perform other actions here. }, )
Finally, we visualize the result
I hope this helps you and have a great day