import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String selectedCountry;
String selectedState;
List<String> countries = ["USA", "Canada", "UK"];
Map<String, List<String>> states = {
"USA": ["New York", "California", "Texas"],
"Canada": ["Ontario", "Quebec", "British Columbia"],
"UK": ["London", "Manchester", "Birmingham"]
};
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reset Second Dropdown Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// First dropdown for selecting country
DropdownButton<String>(
value: selectedCountry,
hint: Text("Select Country"),
onChanged: (value) {
setState(() {
selectedCountry = value;
// Reset selected state when country changes
selectedState = null;
});
},
items: countries.map((country) {
return DropdownMenuItem<String>(
value: country,
child: Text(country),
);
}).toList(),
),
SizedBox(height: 20.0),
// Second dropdown for selecting state
DropdownButton<String>(
value: selectedState,
hint: Text("Select State"),
onChanged: (value) {
setState(() {
selectedState = value;
});
},
// Only show items if a country is selected
items: selectedCountry != null
? states[selectedCountry].map((state) {
return DropdownMenuItem<String>(
value: state,
child: Text(state),
);
}).toList()
: [],
),
],
),
),
);
}
}
In this code, when the value of the first dropdown i.e country changes, the setState method is called to update the state variable selectedCountry. The selectedState variable is reset to null to ensure that the second dropdown i.e state is cleared. As a result, when the first dropdown is changed, the second dropdown will be reset and will only display options related to the newly selected country.