flutter - 如何在flutter中从API中选择索引并分别删除它的数据?
问题描述
我从 API 获取图像并将它们显示到网格视图中,但要求是我长按图像的任何索引,所选图标应该在该索引图像上可见。但问题是,当我在任何索引处长按时,所选图标在所有索引上都可见。
截屏:
为了解决这个问题,我创建了模型类,其中的数据类型首先是每个索引的布尔变量(isSelected),另一个是从 API 获取的 PhotoDetails,但无法处理它FutureBuilder
,因为它在我重建构建方法时执行setState
并且 isSelected 变为 false。
代码:
型号类:
class Photos{
PhotoDetail photoDetail;
bool isSelected;
Photos({this.photoDetail, this.isSelected});
}
未来建造者:
Expanded(
child: FutureBuilder<PhotoModel>(
future: _photoApi.getPhotosByUserList(
token: widget.tokenId,
contactId: widget.userContent.id,
),
builder:(BuildContext context, AsyncSnapshot<PhotoModel> snapshot){
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError){
return Center(child: new Text('Error: ${snapshot.error}'));
}
List<Photos> photos =[];
snapshot.data.content.forEach((element) {
photos.add(
Photos(
isSelected: false,
photoDetail: element
)
);
});
print("photos photos photos length:${photos.length}");
return photos.length>0?
sliverGridWidget(context,photos)
:Container(
alignment: Alignment.center,
child: Text("Empty"),
);
}
)
)
网格视图中的图像:
Widget sliverGridWidget(BuildContext context, List<Photos> listPhotoDetail){
return StaggeredGridView.countBuilder(
padding: const EdgeInsets.all(8.0),
crossAxisCount: 6,
itemCount: listPhotoDetail.length,
itemBuilder: (context, index){
return InkWell(
onLongPress: (){
setState(() {
enable = true;
print("iinnndexxxxxxx:$index");
// listPhotoDetail[index].isSelected = true;
});
},
child: Container(
alignment: Alignment.bottomRight,
decoration: BoxDecoration(
color:Colors.grey[100],
image: DecorationImage(
image: NetworkImage(listPhotoDetail[index].photoDetail.image.fileUrl),
fit: BoxFit.cover
)
),
child:enable?
Image.asset('assets/icons/selected.png')
:Container()
),
);
},
staggeredTileBuilder: (index)=> view ?StaggeredTile.count(6,6):StaggeredTile.count(2,2),
mainAxisSpacing: 8.0,
crossAxisSpacing:8.0,
);
}
解决方案
要解决它,请尝试为每个图像使用特定的键
推荐阅读
- php - 在具有多个类别的单个产品页面上引用类别链接 | 电子商务
- python - 在 Pandas 中使用数组值创建 JSON 键
- java - java - 如何从java中的axis2 webservice请求中获取客户端的IP?
- regex - 在scala中解析case语句
- php - Codeigniter 中的 ERR_CACHE_MISS
- c# - WebAPI 的 404 错误 - 在 HttpModule 中注册路由不起作用
- python - networkx 库的函数 dfs_edges 找不到所有边
- python-3.x - cv2.MORPH_CLOSE 将字母连接在一起
- javascript - 选中复选框时显示文本框并在 php 中发布这两个值
- javascript - Javascript中的图像到Uint8Array