如何在Flutter中为特定列表项增加计数器? [英] How to increment counter for a specific list item in Flutter?

查看:153
本文介绍了如何在Flutter中为特定列表项增加计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像下面的示例图像一样,我想在单击单个列表项的按钮时增加或减少数量。如果我在setState()中增加计数器,则它在每个列表项中都会增加。我需要帮助,尤其是在Flutter中处理特定列表项时。



![示例图像] [2]

任何帮助都将受到赞赏。

预先感谢。



 类FlutterExample扩展了StatelessWidget {
@override
Widget build(BuildContext context){
返回新的Scaffold(
正文:new ListView(
子级:new List.generate(5,(i)=> new ListTileItem(
title: Item#$ i,
)),
),
);
}
}
类ListTileItem扩展了StatefulWidget {
字符串标题;
ListTileItem({this.title});
@override
_ListTileItemState createState()=> new _ListTileItemState();
}

类_ListTileItemState扩展State< ListTileItem> {
int _itemCount = 0;
@override
小部件构建(BuildContext上下文){
返回新的ListTile(
标题:new Text(widget.title),
尾随: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 ++))
],
),
);
}
}


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,

解决方案

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

这篇关于如何在Flutter中为特定列表项增加计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆