i create function of upload image to the app. so i creted repeated button that share same onpressed() future function
class _HomePage5State extends State<HomePage5> {
// This is the file that will be used to store the image
File? _image;
File? _image2;
late String pickerType;
// This is the image picker
final _picker = ImagePicker();
// Implementing the image picker
Future _openImagePicker(String pickerType,File? pImage )
async {
XFile? pickedImage ;
switch (pickerType) {
case "gallery":
/// GALLERY IMAGE PICKER
pickedImage = await _picker.pickImage(
source: ImageSource.gallery);
break;
case "camera": // CAMERA CAPTURE CODE
pickedImage = await _picker.pickImage(
source: ImageSource.camera);
break;
}
if (pickedImage != null) {
setState(() {
debugPrint("SELECTED IMAGE PICK $pickedImage");
pImage = File(pickedImage!.path);
});
} else {
print("You have not taken image");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(35),
child: Column(children: [
Center(
// this button is used to open the image picker
child: ElevatedButton(
onPressed: () {
_settingModalBottomSheet(context, _image);
},
child: const Text('Select An Image'),
),
),
const SizedBox(height: 35),
// The picked image will be displayed here
Container(
alignment: Alignment.center,
width: double.infinity,
height: 300,
color: Colors.grey[300],
child: _image != null
? Image.file(_image!, fit: BoxFit.cover)
: const Text('Please select an image'),
),
Center(
// this button is used to open the image picker
child: ElevatedButton(
onPressed: () {
_settingModalBottomSheet(context , _image2);
},
child: const Text('Select An Image'),
),
),
const SizedBox(height: 35),
// The picked image will be displayed here
Container(
alignment: Alignment.center,
width: double.infinity,
height: 300,
color: Colors.grey[300],
child: _image2!= null
? Image.file(_image2!, fit: BoxFit.cover)
: const Text('Please select an image'),
)
]),
),
));
}
i also create setting modal for repeated variable too, so i dont have to copy same function for every variable i have
void _settingModalBottomSheet(context , File? _imag) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return Wrap(
children: <Widget>[
ListTile(
title: const Text('Gallery'),
onTap: () => {
_openImagePicker("gallery", _imag),
Navigator.pop(context),
}),
ListTile(
title: const Text('Camera'),
onTap: () => {
_openImagePicker("camera", _imag),
Navigator.pop(context)
},
),
],
);
});
}
but when i run the project, seems like future function didn’t return image file value so image container still null/empty
2
Answers
var value=await _openImagePicker();
you got null because you are set wrong variable.
_openImagePicker()
as Future<File?> function.show dialog is also a Future function. you can actually call the
_openImagePicker()
inside the dialog. but i prefer separate them.now use it :