Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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:

  1. Create a class that extends StatefulWidget and define a state object that contains the selected value of the dropdown list.
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,
    );
  }
}
  1. Wrap the DropdownWidget with an InheritedWidget or Provider, and pass the current state of the dropdown as a value.
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(),
      ),
    );
  }
}
  1. In the different class where you want to retrieve the selected value, use the static method of the InheritedWidget or Provider to access the current state of the dropdown.
class AnotherClass extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final selectedValue = DropdownState.of(context).selectedValue;
    return Text('Selected value: $selectedValue');
  }
}