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 i
Add this code as a children of your Column or Row:
itemData[index].ShouldVisible?
Center(
child: Container(
height: 30,
width: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
border: Border.all(color: Colors.white70)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
InkWell(
onTap: (){
setState(() {
if(itemData[index].Counter <2)
{
itemData[index].ShouldVisible = !itemData[index].ShouldVisible;
}else{
itemData[index].Counter--;
}
});
}
,child: Icon(Icons.remove,color: Colors.green,size: 18,)),
Text('${itemData[index].Counter}',style: TextStyle(
color: Colors.white70
),
),
InkWell(
onTap: (){
setState(() {
itemData[index].Counter++;
});
}
,child: Icon(Icons.add,color: Colors.green,size: 18,)),
],
),
)
) : Center(
child: Container(
padding: EdgeInsets.all(5),
height: 30,
width: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
border: Border.all(color: Colors.white70)
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('ADD',style: TextStyle(color: Colors.white70),
),
InkWell(
onTap: (){
setState(() {
itemData[index].ShouldVisible = ! itemData[index].ShouldVisible;
//
});
}
,child: Center(child: Icon(Icons.add,color: Colors.green,size: 18,)))
],
),
),
)
Add Counter and ShouldVisible to your DataStructure as shown below.
class ItemData{
String Name;
int Counter;
bool ShouldVisible;
ItemData({
this.Name,
this.Counter,
this.ShouldVisible
});
}
List<ItemData> itemData = [
ItemData(
Name: 'Shoes 1',
Counter: 1,
ShouldVisible: false
),
ItemData(
Name: 'Shoes 2',
Counter: 1,
ShouldVisible: false
),];
All you need to do is to refactor your widgets the proper way. You can refactor your Card
s / 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++))
],
),
);
}
}