I have an Image widget which displays images in ListView. My purpose is to enable the user to remove the image(One by one) using onRemove() and rebuild the Widget. I’m unable to remove the image itself. The ImagePreview Widget displays the images without issue. Here is the code itself.
// The setPostImage function gets called after picking images from Gallery/Camera. The setPost Image in turn calls the PostImagePreviewer widget which has a onRemove().
void _setPostImage(
required List<PlatformFile> pickedimages2}) {
if (!mounted) {
return;
}
setState(() {
myImageList = List.from(pickedimages2);
int index = myImageList.length - 1;
var postimageWidget = PostImagePreviewer(
key: Key(myImageList[index].name),
postImageFile: myImageList,
onRemove: (int _index) {
_removePostImage(myImageList[_index]);
},
);
_postImageWidgetRemover = _addPostItemWidget(postimageWidget);
//Note -->> _postImageWidgetRemover is initialized a late VoidCallback//
});
}
//This is the Image Previewer Widget.
class PostImagePreviewer extends StatelessWidget {
final List<PlatformFile>? postImages;
final void Function(int index)? onRemove;
const PostImagePreviewer(
{super.key,
this.postImages,
this.onRemove,
});
@override
Widget build(BuildContext context) {
return SizedBox(
height: 400,
child: ListView.builder(
scrollDirection: Axis.horizontal,
physics: const PageScrollPhysics(),
padding: EdgeInsets.zero,
shrinkWrap: true,
itemCount: postImages!.length,
itemExtent: 250,
itemBuilder: (context, index) {
return Stack(
children: <Widget>[
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(6),
topRight: Radius.circular(6),
bottomLeft: Radius.circular(6),
bottomRight: Radius.circular(6)),
child: Image.file(
File(postImages?[index].path ?? ""),
fit: BoxFit.cover,
height: 325,
width: 225,
),
),
Positioned(
top: 10,
right: 35,
child: _buildRemoveButton(index),
),
],
);
},
),
);
}
Widget _buildRemoveButton(int index) {
return GestureDetector(
onTap: () => onRemove?.call(index),
child: SizedBox(
width: buttonSize,
height: buttonSize,
child: const Icon(
IconData(nativeIcon: Ionicons.close_outline),
color: Colors.white,
customSize: 30,
),
));
}
}
// Note---> I couldnt find a way to delete PlatformFile image so converted to File object.
void _removePostImage(PlatformFile image) {
setState(() {
final File imagefileForDeletion = File(image.path.toString());
deleteFile(imagefileForDeletion);
_hasImage = false;
_postImageWidgetRemoverMulti();
});
}
Future<void> deleteFile(File file) async {
try {
if (await file.exists()) {
file.delete();
}
} catch (e) {
// Error in getting access to the file.
}
}
Help appreciated.