动态生成下拉按钮并更改值

时间:2019-07-12 20:53:58

标签: flutter dart dropdown

我正在尝试在我的应用程序中列出几个下拉按钮。虽然我可以轻松生成按钮,但是值无法更新(用户可以选择新值,但按钮不会更改)。

我创建了一个列表,其中包含具有下拉按钮的所有行,以及一个列表,其中包含每个下拉按钮的所有值。每次用户按下特定按钮时,都会向列表添加新行(显示在列中),并调用setState。我确保值实际上会更改并指向正确的索引,但是似乎没有任何作用。对不起,奇怪的格式。如果我遗漏了一些东西,请告诉我。

class MyClassState extends State<MyClass> {
    List<String> _dropdownLabels; 

    List<Widget> _dropdownRows; 

    Widget _dropwdownRow(index) {

      //this is wrapped in a row; I just didn't copy it here

      DropdownButton<String>(
                hint: Text("Unit\n", style: TextStyle(height: .9)),
                value: _dropdownLabels[index],
                onChanged: (String newValue) {
                  setState(() {
                    print("Updated " +
                        index.toString() +
                        " aka " +
                        _dropdownLabels[index] +
                        " to " +
                        newValue);
                    _dropdownLabels[index] = newValue;
                    print("Updated " +
                        index.toString() +
                        " to " +
                        _dropdownLabels[index]);
                  });
                },
                items: Unit.values //unit is defined in my model file; this part works fine
                    .toList()
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),
    }

@override
  void initState() {
    super.initState();
    _dropdownLabels = [""];
    _dropdownRows = [];
    () async {
      //have to do it like this because need to use theme, but it is not initalized yet
      await Future.delayed(Duration.zero);
      _dropwdownRows.add(_dropwdownRow(0));
      setState(() {});
    }();
  }


@override
  Widget build(BuildContext context) {
   return Scaffold(
body: ListView(
    ...
    MaterialButton(
                  child: Icon(Icons.add),
                  color: Theme.of(context).accentColor,
                  shape: CircleBorder(),
                  onPressed: () {
                    setState(() {
                      _dropwdownLabels.add("");
                      _dropwdownRows
                          .add(_dropwdownRow(_dropdownRows.length));
                    });
                  },
                )
    Column(
    children: _dropdownRows,
)
    ...
)

)

}

model.dart类中定义的单位:

const Map<String, String> Unit = {
  "none" : "",
  "teaspoon": "tsp",
  "tablespoon": "tbsp",
  "fluid ounce": "fl oz",
  "other": "other",
};

在此先感谢您的帮助!

0 个答案:

没有答案