Home > front end >  Using enum and ValueNotifier for DropdownMenu in Flutter
Using enum and ValueNotifier for DropdownMenu in Flutter

Time:03-02

Hi what my goal is to display enum values inside of a dropdown menu and to replace setState with ValueNotifier and ValueListenableBuilder. I'm fairly new to flutter and currently I only know how to display dropdown menu when we have a list of strings and its using setState but how can I modify it. So for instance we have enum Locations={belgium,germany,spain, etc}

This is my code so far:

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('hi'),
      ),
      drawer: FoodNotifyDrawer('name'),
      body: Container(
        padding: EdgeInsets.all(7),
        child: Center(
          child: Column(
            children: [
              SizedBox(
                height: 40,
              ),
              DropdownButton(
                // Not necessary for Option 1
                value: _selectedLocation,
                onChanged: (String? newValue) {
                  setState(() {
                    _selectedLocation = newValue;
                  });
                },
                items: _locations.map((location) {
                  return DropdownMenuItem(
                    child: Text(location),
                    value: location,
                  );
                }).toList(),
              ),
              SizedBox(
                height: 40,
              ),
              Text('Option 2'),
              SizedBox(
                height: 40,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Any help would be great, thanks in advance :)

CodePudding user response:

Yes you can; you can use the same enum values as the values of your dropdown, as in this enter image description here

The rest should be straight forward using ValueNotifier and setState.

CodePudding user response:

import 'package:flutter/material.dart';

enum Locations { belgium, germany, spain }

class DropDownTest extends StatelessWidget {
DropDownTest({Key? key}) : super(key: key);
final ValueNotifier<Locations> _selectedValue =
  ValueNotifier<Locations>(Locations.belgium);
@override
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: ValueListenableBuilder<Locations>(
        valueListenable: _selectedValue,
        builder: (context, v, _) {
          return DropdownButton<Locations>(
            value: v,
            onChanged: (Locations? newValue) {
              if (newValue != null) {
                _selectedValue.value = newValue;
              }
            },
            items: Locations.values.map((d) {
              return DropdownMenuItem(
                child: Text(d.name),
                value: d,
              );
            }).toList(),
          );
        }),
      ),
    );
    }
   }
  • Related