0

DropdownButton doesn't reflect menuItem's changes when the dropdown menu is open.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final disabledItems = ['Free', 'Four'];

  List<String> items = ['One', 'Two', 'Free', 'Four'];

  String dropdownValue = 'One';

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      icon: Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String newValue) {
        if (!disabledItems.contains(newValue)) {
          setState(() {
            dropdownValue = newValue;
          });
        }
      },
      items: items.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Row(children: [
            Text(
              value,
              style: TextStyle(
                color: disabledItems.contains(value) ? Colors.grey : null,
              ),
            ),
            IconButton(
              icon: Icon(Icons.delete),
              color: Colors.black38,
              onPressed: () {
                setState(() {
                  items.removeWhere((element) => element == 'Two');
                });

                print(items.length);
              },
            )
          ]),
        );
      }).toList(),
    );
  }
}

What I aim is the chance of removing an item from the menu when the delete icon is pressed. All the expected events are working as expected and the DropDown items list is updating accordingly in the backend but it doesn't re-render. DorpDown Menu with delete icon

In order to be able to see the updated items list I have to close the dropdown menu and open it again but this doesn’t feel right in terms of user experience.

Daniel
  • 31
  • 2

0 Answers0