How to increment counter for a specific list item

2020-03-25 12:49发布

问题:

Like in my sample image, below, I want to increment or decrement quantity upon button click for single list item. If I increase the counter in setState(), its incrementing in every list item. I need help with this, especially in handling specific list item in Flutter.

![Sample Image][2]
Any help is appreciated.
Thanks in advance.

Got the List Item Thanks for the help,

回答1:

All you need to do is to refactor your widgets the proper way. You can refactor your Cards / items into their separate StatefulWdiget such that each increment/decrement affect only a specific item and not the whole list.

Check this example :

class FlutterExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new ListView(
        children: new List.generate(5, (i)=>new ListTileItem(
          title: "Item#$i",
        )),
      ),
    );
  }
}
class ListTileItem extends StatefulWidget {
  String title;
  ListTileItem({this.title});
  @override
  _ListTileItemState createState() => new _ListTileItemState();
}

class _ListTileItemState extends State<ListTileItem> {
  int _itemCount = 0;
  @override
  Widget build(BuildContext context) {
    return new ListTile(
      title: new Text(widget.title),
      trailing: new Row(
        children: <Widget>[
           _itemCount!=0? new  IconButton(icon: new Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--),):new Container(),
            new Text(_itemCount.toString()),
            new IconButton(icon: new Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
        ],
      ),
    );
  }
}


标签: dart flutter