So essentially I have a form class in a flutter application. The user could upload a set of images onto the form, and then submit for certain operations to be done to those images. The two functionalities are handled by two async functions, selectImages
and mystery
. However, the fact that images were “selected” in selectImages
(represented by the population of list imageFileList
) is not registered in mystery
.
Here is the relevant code for the Form Class
class MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context){
final ImagePicker imagePicker = ImagePicker();
List<XFile>? imageFileList = [];
void mystery() async {
print("Image list length in mystery " + imageFileList.length.toString());
for (XFile? image in imageFileList){
/* perform operations */
}
}
/* prompts the user to select multiple images and stores them in imageFileList */
selectImages() async {
final List<XFile>? selectedImages = await
imagePicker.pickMultiImage();
if (selectedImages.isNotEmpty) {
imageFileList.addAll(selectedImages);
}
print("Image List Length in SelectImages:" + imageFileList.length.toString());
setState((){});
}
return Form(
key: _formKey,
child: Column(
children: [
Row(
children: [
Column(
children: [
Text("Image:", style: TextStyle(fontWeight : FontWeight.bold,)),
IconButton(onPressed: (){
selectImages();
}, icon : /* icon */
)
],
),
],
),
/*SUBMIT BUTTON*/
Padding(
padding: /* padding */,
child: ElevatedButton(
onPressed: () {
/*if the SUBMIT button is pressed, performs operations */
if (_formKey.currentState!.validate()){
print("Image List Length in OnPressed " + imageFileList!.length.toString());
mystery();
}
},
child: const Text('Submit')
),
),
],
),
);
}
}
and here is the output when I use the form:
Image List Length in SelectImages:2
Image List Length in OnPressed 0
Image list length in mystery 0
As can be seen, the state of imageFileList is only updated within SelectImages, but is not updated elsewhere.
The issue is probably due to the fact that SelectImages is asynchronous; however, I am new to asynchronous functions, and hence I do not know exactly what to do in this situation. Any assistance will be appreciated.