android - 如何使用重复项编辑列表项
问题描述
我有一个动态列表,其ListView.builder() & ListTile()
方法可能包含重复项,我想编辑一个项目,但我的问题是它检查列表中该值的第一次出现。
要进行编辑,我的列表图块中有 longpress 属性,它会打开一个警报对话框进行编辑
例如(也请参阅图像):[a,b,c,d,a] 我想在索引 4 处编辑 'a' 让我们说' e',但我的程序编辑了它的第一次出现。
final _items = List();
final TextEditingController addeditem = TextEditingController(text: ''); // for adding items
final TextEditingController editeditem = TextEditingController(text: ''); // for editing items
// I have an alert dialog where there is an input field and button to edit the
TextField(
decoration: InputDecoration(
hintText: 'Edit Item',
),
controller: editeditem,
),
TextButton(
child: Text('Done'),
onPressed: (){
_editItem(); // this calls the edit item logic
Navigator.of(context).pop();
}
)// alert dialog ends here
// edit item logic
void _editItem(){
setState(() {
int target = 0;
for(int i=0; i<index; i++){ // I am new to dart and don't know the function right now
if(_items[i] == value){ // so hard coded a for loop for checking selected item
target = i; // and replace it
break;
}
}
_items[target] = editeditem.text; // text editing controller to replace item with new value
});
问候,
解决方案
我建议您创建一个将用作对象的类,然后覆盖 equals 方法以验证唯一项目的身份(您也可以使用https://pub.dev/packages/equatable)。
例子:
class Item extends Equatable {
final int id; // unique key to differance the object
String text;
// It will check with this id for the unique value
@override
List<Object> get props => [this.id];
}
现在,您将这个项目类用于您的列表,该列表仅包含一个字符串。
void _editItem(){
setState(() {
this._items[this._items.indexOf(value)].text = editeditem.text;
}
或者你也可以将点击的 ListTile 的索引传递给编辑函数,然后你可以像这样修改:
void _editItem(int index){
setState(() {
this._items[index] = editeditem.text;
}
希望对你有帮助
推荐阅读
- javascript - 如何在 React 中按另一个过滤数组?
- swift - 添加新项目时为 CAShapelayer 内容设置动画
- java - Java运行命令无法连接Oracle数据库?
- hadoop - 使用 bicond 获取 ID?
- postgresql - 如何使用 Ansible 替换文件中的多个相同行
- python-3.x - 如何给数字一个特定的颜色并使用 PIL 显示它?
- c - 在 C 中使用 OR 的 switch 语句
- javascript - 如何停止来自子元素的链接的默认行为
- python - ValuError:检查目标时出错:预期activation_6具有形状(70,)但得到形状为(71,)的数组
- php - 如何使用不同主题的不同电子邮件在同一功能中两次调用 wp_mail()?