'Flutter widget unmounting without dispose
So a piece of code I wrote needs to run on both web and mobile. And since some libraries like dart: io on the web and can't use dart:html on mobile. So in order to pick images on the web, I tried to use ImagePicker which returns an X-File, turns the X-File to bytes, and uses Image. memory().
This is the piece of code that I've been trying:
class _CanvasImageItemState extends State<CanvasImageItem> {
Uint8List? imageBytes;
XFile? file;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
// widgets
}
Widget buildPicker(BuildContext context) {
if (kDebugMode) {
print("picker loaded");
}
return InkWell(
onTap: () async {
FocusedItemModel.of(context).focus(widget.item as LocalImageItem);
if (!kIsWeb) {
// Some piece of code for mobile
} else {
await _pickImage();
}
},
child: ..some other widgets
);
}
}
_pickImage() async {
final ImagePicker _picker = ImagePicker();
file = await _picker.pickImage(source: ImageSource.gallery);
Uint8List? bytes = await file!.readAsBytes();
if (mounted) {
setState(() {});
imageBytes = bytes;
} else {
imageBytes = bytes;
}
if (kDebugMode) {
print("Checking File: ${file!.path}");
print("Checking imageBytes: ${imageBytes!.length}");
}
}
The problem is although I did not dispose() the widget or used dispose() anywhere in the project itself but I am getting
setState() called after dispose() error. So I tried checking if(mounted) before trying to update the value of imageBytes but in that case, it's taking two tries to pick the image.
As you can see I even tried to print the path of xFile and imageBytes which is getting printed properly. But I cannot set the state.
N.B: The CanvasImageItem is child of another widget called CanvasMovableItem. Any suggestion where the problem is occurring from? I've checked all possible codes that might unmount or dispose of the widget.
Am I missing something very simple?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
