To create two separate dropdown menus that are dependent on each other in Flutter, you can use the DropdownButton and DropdownMenuItem widgets along with state management.
Here's an example:
import 'package:flutter/material.dart';
class DropdownSearchExample extends StatefulWidget {
@override
_DropdownSearchExampleState createState() => _DropdownSearchExampleState();
}
class _DropdownSearchExampleState extends State<DropdownSearchExample> {
String dropdownValue1;
String dropdownValue2;
Map<String, List<String>> options = {
'Option 1': ['Option 1-1', 'Option 1-2', 'Option 1-3'],
'Option 2': ['Option 2-1', 'Option 2-2', 'Option 2-3'],
'Option 3': ['Option 3-1', 'Option 3-2', 'Option 3-3'],
};
List<DropdownMenuItem<String>> buildDropdownMenuItems() {
List<DropdownMenuItem<String>> items = [];
options.keys.forEach((key) {
items.add(DropdownMenuItem<String>(
value: key,
child: Text(key),
));
});
return items;
}
List<DropdownMenuItem<String>> buildDropdownMenuItems2() {
List<DropdownMenuItem<String>> items = [];
if (dropdownValue1 != null) {
List<String> values = options[dropdownValue1];
values.forEach((value) {
items.add(DropdownMenuItem<String>(
value: value,
child: Text(value),
));
});
}
return items;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Search Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: DropdownButton<String>(
value: dropdownValue1,
hint: Text('Select Option 1'),
onChanged: (String newValue) {
setState(() {
dropdownValue1 = newValue;
dropdownValue2 = null; // Reset value for the second dropdown
});
},
items: buildDropdownMenuItems(),
),
),
SizedBox(height: 16),
Center(
child: DropdownButton<String>(
value: dropdownValue2,
hint: Text('Select Option 2'),
onChanged: (String newValue) {
setState(() {
dropdownValue2 = newValue;
});
},
items: buildDropdownMenuItems2(),
),
),
],
),
);
}
}
void main() {
runApp(MaterialApp(
home: DropdownSearchExample(),
));
}
In this example, we have a stateful widget DropdownSearchExample with two dropdowns. The options for the second dropdown depend on the selected value of the first dropdown. The available options are stored as a Map where the keys are the values of the first dropdown and the values are the options for the second dropdown.
The buildDropdownMenuItems method is used to build the DropdownMenuItem list for the first dropdown. Similarly, the buildDropdownMenuItems2 method builds the list for the second dropdown based on the selected value of the first dropdown. These methods are called in the items property of the respective DropdownButton widgets.
When a value is selected in the first dropdown, the onChanged callback updates the state and triggers a rebuild, which updates the options for the second dropdown based on the selected value.
Remember to run this code within a Flutter project and import the necessary Flutter packages.