【问题标题】:Drop down inside ListView in flutter在颤动中下拉列表视图
【发布时间】:2020-01-25 11:56:31
【问题描述】:

每当我从下拉列表中选择时,我在 ListView.Builder 中有 DropDownButton,它会给出更改值,但不会反映在 UI 上。

 List _warranty = ["NONE","1 YEAR", "2 YEAR"];
 List<DropdownMenuItem<String>> getDropDownWarranty() {
      List<DropdownMenuItem<String>> items = new List();
      for (String str in _warranty) {
        items.add(new DropdownMenuItem(
            value: str,
            child: new Text(
              str,
              style: TextStyle(color: Colors.white, fontFamily: 'semibold'),
            )));
      }
      return items;
    }

这是我的 ListView 项目小部件

  Widget item(AsyncSnapshot<CartBean> snapshot, int index) {
      String _current = "";
      return Column(
        children: <Widget>[
          Container(
            height: 40,
            decoration: BoxDecoration(color: MyColors.cartback),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  width: SizeConfig.screenWidth / 1.7,
                  padding: EdgeInsets.all(SizeConfig.blockSizeHorizontal * 2),
                  decoration: BoxDecoration(
                    color: MyColors.colorLightPrimary,
                  ),
                  child: snapshot.data.data[index].lcwInfo.length > 0
                      ? Theme(
                    data: Theme.of(context).copyWith(
                        brightness: Brightness.dark,
                        canvasColor: MyColors.colorPrimary),

                    child: dropDown(snapshot.data.data[index].lcwInfo,
                        _current,index), // Your Dropdown Code Here,
                  )
                      : FlatButton(
                    onPressed: () {},
                    padding: EdgeInsets.all(0),
                    child: Text(
                      "EXTEND WARRANTY",
                      style: TextStyle(
                          color: Colors.grey[300],
                          fontFamily: "semibold"),
                    ),
                  ),
                ),
                FlatButton.icon(
                  onPressed: () {
                    removeCartItemService(
                        snapshot.data.data[index].productId, index);
                  },
                  icon: Image.asset(
                    'assets/icons/cancel.png',
                    width: 28,
                    height: 28,
                  ),
                  label: Text(''),
                )
              ],
            ),
          ),
        ],
      );
    }

这个方法在ListViewItem 小部件中调用

 Widget dropDown(List<LcwInfo> list, String _current,int index) {
      List<DropdownMenuItem<String>> _dropDownWarranty;
      _dropDownWarranty = getDropDownWarranty();
      _current = _dropDownWarranty[0].value;

      if (list.length > 0) {
        return DropdownButtonHideUnderline(
          child: DropdownButton<String>(
            value: _dropDownWarranty[0].value,
            items: _dropDownWarranty,
            onChanged: (String onValue) {
              debugPrint("CURRENT VALUE:----------${onValue}");
              updateWarrantyService(index,onValue,list[0]);
              setState(() {
                _dropDownWarranty[0] = onValue as DropdownMenuItem<String>;
              });
            },
          ),
        );
      }
    }

以上所有方法都在build(BuildContext context)中声明

【问题讨论】:

    标签: android ios flutter dart


    【解决方案1】:

    我用selectedItemValue 创建了一个变量来将选定的值存储在DropdownButton 中,在我将默认值设置为无所有项目之前。

        class ListViewDemo extends StatefulWidget {
        @override
        State<StatefulWidget> createState() {
            return ListViewDemoState();
        }
        }
    
        class ListViewDemoState extends State<ListViewDemo> {
        List<String> selectedItemValue = List<String>();
    
        @override
        void initState() {
            // TODO: implement initState
            super.initState();
        }
    
        @override
        Widget build(BuildContext context) {
            return Scaffold(
                appBar: AppBar(
                title: Text("ListView"),
                ),
                body: Column(
                children: <Widget>[
                    Expanded(
                    child: ListView.builder(
                        itemCount: 20,
                        itemExtent: 50.0,
                        itemBuilder: (BuildContext context, int index) {
                            for (int i = 0; i < 20; i++) {
                            selectedItemValue.add("NONE");
                            }
                            return DropdownButton(
                            value: selectedItemValue[index].toString(),
                            items: _dropDownItem(),
                            onChanged: (value) {
                                selectedItemValue[index] = value;
                                setState(() {});
                            },
                            hint: Text('Select Gender'),
                            );
                        }),
                    )
                ],
                ));
        }
        }
    
        List<DropdownMenuItem<String>> _dropDownItem() {
        List<String> ddl = ["NONE", "1 YEAR", "2 YEAR"];
        return ddl
            .map((value) => DropdownMenuItem(
                    value: value,
                    child: Text(value),
                ))
            .toList();
        }
    

    【讨论】:

    • 你不知道这对我有什么帮助。这段代码让我很开心。非常感谢,@Amit Prajapati 兄弟。它完全按预期工作。
    【解决方案2】:

    如果调用 setState 时所有这些都在构建内部,这将重置包括变量在内的值。

    在您的情况下,_dropDownWarranty = getDropDownWarranty(); 将在每次调用 setState 时将 _dropDownWarranty 的值设置为 getDropDownWarranty();,而不管它在 onChanged 中设置为什么。

    我建议将_dropDownWarranty = getDropDownWarranty(); 移到build 之外,但仍在课堂内。事实上,我建议将函数移到 build 方法之外,但通常将它们保留在类中,否则每次调用 setState 时它们都会重新运行!

    这个例子展示了如何设置值,但在构建方法https://stackoverflow.com/a/54948635/4644407中没有它

    【讨论】:

    • 我移动了所有与dropDown相关的代码仍然没有影响
    • 实际上我的所有代码都保存在构建方法之外,但我在 SO 上找到了一种解决方案,建议我将代码保存在构建小部件中
    • @FarhanaNaazAnsari 你好我有同样的问题.. 我想要下拉列表项
    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2019-04-08
    • 1970-01-01
    • 2019-11-30
    • 2020-11-20
    • 2020-06-19
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多