I have so many data to send to my backend. I made a class for all data I need. I named it service_data
and it contains
class ServiceData {
File? fileBukuServis;
File? fileSTNK;
File? fileOwnerManual;
}
after that, I want to pick image from camera and set it into the data above. I use package image_picker
and I use this function to set the data
class _DetailCarState extends State<DetailCar> {
ServiceData serviceData = ServiceData();
final ImagePicker _picker = ImagePicker();
Future pickImage({File? imageData, html.File? htmlImageData}) async {
final XFile? image =
await _picker.pickImage(source: ImageSource.camera, imageQuality: 50);
if (image != null) {
setState(() {
imageData = File(image.path);
});
}
if (kDebugMode) {
print(serviceData.fileBukuServis!.path);
}
}
}
and for pick image, I use this
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.red[800])),
onPressed: () {
if (kIsWeb) {
pickImage(htmlImageData: serviceData.htmlfileBukuServis);
}
pickImage(imageData: serviceData.fileBukuServis);
},
child: const Text('Ambil gambar'))
and when I pict image from camera, fileBukuServis
inside serviceData
always null. How can I set the data from imagepicker?
In the method you use to pick the image, you just modify the local variable imageData
and return nothing.
Future pickImage({File? imageData, html.File? htmlImageData}) async {
final XFile? image =
await _picker.pickImage(source: ImageSource.camera, imageQuality: 50);
if (image != null) {
setState(() {
imageData = File(image.path); // Won't do anything since variable is in local scope
});
}
if (kDebugMode) {
print(serviceData.fileBukuServis!.path);
}
}
You can directly change the serviceData.fileBukuServis
variable. Here is the modified code:
class ServiceData {
File? fileBukuServis;
File? htmlfileBukuServis;
File? fileSTNK;
File? fileOwnerManual;
}
enum ServiceDataFile{
fileBukuServis,
htmlfileBukuServis,
}
class _DetailCarState extends State<DetailCar> {
ServiceData serviceData = ServiceData();
final ImagePicker _picker = ImagePicker();
Future pickImage(ServiceDataFile fileMode) async {
final XFile? image =
await _picker.pickImage(source: ImageSource.camera, imageQuality: 50);
if (image != null) {
if(fileMode == ServiceDataFile.fileBukuServis){
serviceData.fileBukuServis = File(image.path);
} else {
serviceData.htmlfileBukuServis = File(image.path);
}
setState((){});
if(kDebugMode){
print(image.path);
}
}
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.red[800]),
),
onPressed: () {
pickImage(kIsWeb ? ServiceDataFile.htmlfileBukuServis : ServiceDataFile.fileBukuServis);
},
child: const Text('Ambil gambar'),
);
}
}
Also, your ServiceData
class didn't have a htmlfileBukuServis
field. Make sure to add it in your code.