0

当下拉菜单打开时,DropdownButton 不会反映 menuItem 的更改。

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(),
    );
  }
}

我的目标是在按下删除图标时有机会从菜单中删除一个项目。所有预期的事件都按预期工作,并且 DropDown 项目列表在后端相应更新,但不会重新呈现。 带有删除图标的 DorpDown 菜单

为了能够看到更新的项目列表,我必须关闭下拉菜单并再次打开它,但这在用户体验方面感觉不对。

4

0 回答 0