Show menu

main.dart

  void main() => runApp(DemoApp());

  class DemoApp extends StatelessWidget {
    const DemoApp();

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Dropdown Example"),
          ),
          body: ChangeNotifierProvider<DropdownText>(
            create: (_) => DropdownText(),
            child: Center(
              child: const SizedBox(
                width: 250,
                height: 100,
                child: DropDown(),
              ),
            ),
          ),
        ),
      );
    }
  }
  

dropdown_provider.dart

  class DropdownText with ChangeNotifier {
    static final _list = ["Pasta", "Pizza", "Maccheroni"]
        .map<DropdownMenuItem<String>>((item) {
      return DropdownMenuItem<String>(
        value: item,
        child: Text(item),
      );
    })
        .toList();

    final menuItems = UnmodifiableListView(_list);

    var _text = "";
    String get text => _text;

    void setText(String value) {
      _text = value;
      notifyListeners();
    }
  }
  

dropdown_button.dart

  class DropDown extends StatelessWidget {
     const DropDown();

    @override
    Widget build(BuildContext context) {
      return Consumer<DropdownText>(
        builder: (context, dropdown, _) {
          return DropdownButtonFormField<String>(
            items: dropdown.menuItems,
            value: dropdown.text,
            onChanged: (value) {
              dropdown.setText(value);
            },
          );
        },
      );
    }

  }
  

This website and the book are not official Google products. No affiliations are involved. Built with Java 14 and Vert.X

"Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC"