就像在下面的示例图像中一样,我想在按钮单击单个列表项时增加或减少数量.如果我在setState()中增加计数器,它会在每个列表项中递增.我需要帮助,特别是在处理Flutter中的特定列表项时.
![示例图片] [2]
任何帮助表示赞赏.
提前致谢.
得到列表项目 感谢您的帮助,
您需要做的就是以正确的方式重构您的小部件.您可以将Card
s /项重构为单独的,StatefulWdiget
这样每个增量/减量只影响特定项而不影响整个列表.
检查此示例:
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++))
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您打算仅获取 UI 代码。这是构建如此漂亮按钮的代码。
代码:
Container(
padding: EdgeInsets.all(3),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Theme.of(context).accentColor),
child: Row(
children: [
InkWell(
onTap: () {},
child: Icon(
Icons.remove,
color: Colors.white,
size: 16,
)),
Container(
margin: EdgeInsets.symmetric(horizontal: 3),
padding:
EdgeInsets.symmetric(horizontal: 3, vertical: 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
color: Colors.white),
child: Text(
'3',
style: TextStyle(color: Colors.black, fontSize: 16),
),
),
InkWell(
onTap: () {},
child: Icon(
Icons.add,
color: Colors.white,
size: 16,
)),
],
),
),
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5307 次 |
最近记录: |