This code is for picking multiple images from the gallery using Image Picker Package and showing them on the home screen. After that drag one of the image from the selected images and drop it to drop target by removing the dropped image from the list of selected images. But I'm unable to do as it is showing an exception.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Gallery extends StatefulWidget {
const Gallery({Key? key}) : super(key: key);
@override
_GalleryState createState() => _GalleryState();
}
class _GalleryState extends State<Gallery> {
final List<XFile>? selectedImagesList = [];
final List<XFile> dropTargetList = [];
@override
Widget build(BuildContext context) {
double size = 230;
return Scaffold(
appBar: AppBar(
title: const Text('Gallery'),
),
body: Column(
children: [
ElevatedButton(
onPressed: () async {
final List<XFile>? selectedImages = await ImagePicker().pickMultiImage();
if (selectedImages!.isNotEmpty) {
setState(() {
selectedImagesList!.addAll(selectedImages);
});
}
},
child: const Text('Select Images'),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
itemCount: selectedImagesList!.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
itemBuilder: (BuildContext context, int index) {
return Draggable<XFile>(
child: Image.file(File(selectedImagesList![index].path),
fit: BoxFit.cover, width: 230, height: 230),
feedback: Image.file(
File(selectedImagesList![index].path),
fit: BoxFit.cover,
width: 230,
height: 230),
childWhenDragging: Container(
color: Colors.red, width: size, height: size),
);
}),
),
),
Container(
width: size,
height: size,
color: Colors.green,
child: DragTarget<XFile>(
builder: ((context, candidateData, rejectedData) {
return Row(
children: dropTargetList
.map((target) => Image.file(File(target.path),
fit: BoxFit.cover, width: size, height: size))
.toList());
}),
onWillAccept: (data) => true,
onAccept: (data) {
setState(() {
dropTargetList.add(data);
selectedImagesList
?.removeWhere((photo) => photo.path == data.path);
});
})),
const SizedBox(height: 200)
],
),
);
}
}
This is the exception while dropping the image https://i.stack.imgur.com/ParUz.png
Emulator screen getting stuck on dropping https://i.stack.imgur.com/5lEsN.png
CodePudding user response:
To prevent the exception from occuring, make sure to only accept data
if data is not null:
onWillAccept: (data) => data != null,
This will prevent the exception.
Looking further on why data is null, it's because you don't set it when you create your draggable:
return Draggable<XFile>(
child: ...,
...
data: selectedImagesList![index],
);
Now it will work as you expect it to. Dragging multiple images down causes some overflow, but you should be able to work on that with the exception out of your way :)