简体   繁体   English

在 flutter 的 ListView 中下拉

[英]Drop down inside ListView in flutter

I have DropDownButton in ListView.Builder whenever I selected from dropdown it gives on change value but doesn't reflect on UI.每当我从下拉列表中选择时,我在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;
    }

This is my ListView Item widget这是我的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(''),
                )
              ],
            ),
          ),
        ],
      );
    }

This method is calling in ListView Item widget此方法在ListView Item 小部件中调用

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

All Above methods are declared inside build(BuildContext context)以上所有方法都在build(BuildContext context)中声明

在此处输入图像描述

If all of this is inside the build when you call setState this will reset the values including the variables.如果当您调用 setState 时所有这些都在构建中,这将重置包括变量在内的值。

In your case _dropDownWarranty = getDropDownWarranty();在你的情况下_dropDownWarranty = getDropDownWarranty(); is setting the value of _dropDownWarranty to getDropDownWarranty();正在将 _dropDownWarranty 的值设置为_dropDownWarranty getDropDownWarranty(); everytime you call setState regardless of what it is set to in the the onChanged.每次调用 setState 时,无论它在 onChanged 中设置为什么。

I would recommend moving the _dropDownWarranty = getDropDownWarranty();我建议移动_dropDownWarranty = getDropDownWarranty(); outside of the build but within the class still.build之外,但仍在 class 之内。 In fact, I would recommend moving function outside of the build method but keeping them in the class as a rule otherwise they will rerun every time you call setState!实际上,我建议将 function 移到构建方法之外,但通常将它们保留在 class 中,否则每次调用 setState 时它们都会重新运行!

This example shows how to set the value but not having it inside the build method https://stackoverflow.com/a/54948635/4644407此示例显示如何设置值但不在构建方法https://stackoverflow.com/a/54948635/4644407

I have created one variable with selectedItemValue to store selected value in DropdownButton , Before i set default value to None all item.我创建了一个带有selectedItemValue的变量来将所选值存储在DropdownButton中,在我将默认值设置为 None 所有项目之前。

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

在此处输入图像描述

You can try using expansion tile for this which is provided by flutter it.您可以尝试使用 flutter 提供的扩展磁贴。

ExpansionTile(
    title: Text(artistData.artistName),
        children: [
               ListTile(
                    leading: Image(
                    image: NetworkImage(artistData.artworkUrl100),
                        ),
                    title: Text(artistData.collectionName),
                      subtitle: Text(artistData.description),
                    )
                  ],
               );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM