I'm trying to reset the value of a String (dropdownValue) of my DropdownButton class (SomeButton) from another class which is a sibiling. To be more precise, here is some code with comments
Parent (Contains both siblings)
class Parent extends StatelessWidget {
const Parent({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Stackoverflow(),
SomeButton(),
],
);
}
}
Dropdown Class (contains dropdownValue which I want to reset from button class)
class Stackoverflow extends StatefulWidget {
const Stackoverflow({Key? key}) : super(key: key);
@override
State<Stackoverflow> createState() => _StackoverflowState();
}
class _StackoverflowState extends State<Stackoverflow> {
String? dropdownValue;
@override
Widget build(BuildContext context) {
return DropdownButtonHideUnderline(
child: DropdownButton2(
items: someItems,
onChanged: (value) {
setState(() {
dropdownValue = value as String;
});
},
value: dropdownValue),
);
}
}
Button (onTap -> clear dropdownValue from upper class)
class SomeButton extends StatelessWidget {
const SomeButton({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
// reset dropdownValue
},
);
}
}
When I searched for solutions, keys might be an option. But to be honest, I never used keys and saw no explicit documentation for my kind of problem. Provider could also be used, but I had trouble with not initialize my dropdownValue, because I should be empty when no user interaction is done so far. I would appreciate any kind of help :)
CodePudding user response:
You can use callback functions from your parent class.
class Parent extends StatefulWidget {
const Parent({Key? key}) : super(key: key);
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
String? dropdownValue;
@override
Widget build(BuildContext context) {
return Column(
children: [
Stackoverflow(
dropdownValue: dropdownValue,
onChanged: (value) {
setState(() {
dropdownValue = value;
});
},
),
SomeButton(
dropdownValue: dropdownValue,
onTap: () {
//reset dropdownValue to whatever you want
},
),
],
);
}
}