【发布时间】:2019-10-20 16:25:07
【问题描述】:
我有一个 ListView,其中包含自定义的 statefull 小部件作为项目。 这些项目有一个 onTap 事件,可以将图标从 check_box_outline_blank 切换到 check_box,反之亦然。
但是,当我在列表中选择一个项目并向下滚动并再次备份时,该项目已将图标从 check_box 重置为 check_box_outline_blank。
如何防止这种情况发生?
new Expanded(
child: ListView.builder(
itemCount: _list.length,
itemBuilder: (BuildContext context, int index) {
return listTile(_pveList[index], index)
},
)
)
//Adds extra space(height:100) after the last tile
StatefulWidget listTile(String text, int index){
return (index < _pveList.length - 1)?new SelectableListItem(text: text,
onTap: (){
_handleOnTap(text);
},
): new Column(
children: <Widget>[
new SelectableListItem(text: text,
onTap: (){
_handleOnTap(text);
},
),
SizedBox(
height: 100,
)
],
);
}
磁贴小部件(SelectableListItem):
import 'package:flutter/material.dart';
class SelectableListItem extends StatefulWidget {
SelectableListItem({Key key, this.text, this.onTap})
: super(key: key);
final String text;
final GestureTapCallback onTap;
@override
_SelectableListItemState createState() => _SelectableListItemState();
}
class _SelectableListItemState extends State<SelectableListItem> {
bool isSelected = false;
Icon _checked = new Icon(Icons.check_box_outline_blank);
handleOnTap() {
isSelected = !isSelected;
if (isSelected) {
setState(() {
_checked = new Icon(Icons.check_box);
});
} else {
setState(() {
_checked = new Icon(Icons.check_box_outline_blank);
});
}
return widget.onTap();
}
@override
Widget build(context) {
// Pass the text down to another widget
return new GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => handleOnTap(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Padding(
padding: EdgeInsets.all(22),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Text(widget.text, style: TextStyle(fontSize: 18)),
_checked
],
),
),
new Container(
width: double.infinity,
height: 1,
color: Color(0x1a222222),
)
],
),
);
}
}
【问题讨论】:
-
请发布您的
ListView和有状态小部件类的一些代码。 -
@George 我已经用代码示例更新了问题