I was working on a project for which I require the user to select a file from his/her device. The way I did it before flutter updated to enable null safety was that I would initialize an empty file and after the user picks the file the empty file gains the path of the selected file. This was the code to do it -
File myfile;
Future<void> _takePicture() async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(type: FileType.image);
if (result != null) {
PlatformFile file = result.files.first;
setState(() {
myFile = File(file.path.toString());
});
But after I updated flutter to 2.5.2 it started giving an error , 'Non-nullable instance field 'myFile' must be initialized.'. My IDE suggests adding a late modifier before initializing the file, but after picking the file the app crashes due to that. Is there any way around this? Please help
If your variable can be null, then just make it nullable:
File? myfile;
Null-Safety is a great feature to let you see faster and more effective when something can or cannot be null. But some variables can be null. That's totally fine. All null safety requires is that you declare them as such using the question mark as seen above.