To retrieve an already selected value from a dropdown list widget in Flutter from a different class, you can make use of state management techniques such as InheritedWidget or Provider.
Here are the steps you can follow:
class DropdownWidget extends StatefulWidget {
@override
_DropdownWidgetState createState() => _DropdownWidgetState();
}
class _DropdownWidgetState extends State<DropdownWidget> {
String selectedValue;
void onSelect(String value) {
setState(() {
selectedValue = value;
});
}
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: selectedValue,
items: [
DropdownMenuItem(value: 'Option 1', child: Text('Option 1')),
DropdownMenuItem(value: 'Option 2', child: Text('Option 2')),
DropdownMenuItem(value: 'Option 3', child: Text('Option 3')),
],
onChanged: onSelect,
);
}
}
class DropdownState extends InheritedWidget {
final String selectedValue;
DropdownState({required Widget child, required this.selectedValue})
: super(child: child);
static DropdownState of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DropdownState>();
}
@override
bool updateShouldNotify(DropdownState oldWidget) {
return selectedValue != oldWidget.selectedValue;
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DropdownState(
selectedValue: 'Option 1',
child: Scaffold(
appBar: AppBar(title: Text('Dropdown Example')),
body: DropdownWidget(),
),
);
}
}
class AnotherClass extends StatelessWidget {
@override
Widget build(BuildContext context) {
final selectedValue = DropdownState.of(context).selectedValue;
return Text('Selected value: $selectedValue');
}
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-20 11:00:00 +0000
Seen: 8 times
Last updated: Nov 06 '21
What is the process for incorporating std::hash into a class template?
What is the process for adding a class path permanently to the Mac terminal?
How can the __iter__ method of the cursor class in psycopg2 be expanded?
What is the process for obtaining and recording all Linq To Db queries in a database table?
What is the method for directing focus toward the subset within an existing class?
How do I reference media element events located on a ContentView from a ContentPage XAML CS class?
What is the issue when Selenium is unable to locate an element by its class name?
Is there a potential for a conflict between the name of a class and the name of a property?
How to obtain the value of an annotation by using reflection?