I want to upload an image in firebase storage using flutter, but when I did not choose any image there will be an error.
The error started to happen when I put the code that will upload the image. If I also remove the null check, it will also show an error message that it needs a null check.
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:project/storage_service.dart';
class UserProfile extends StatefulWidget {
const UserProfile({super.key});
@override
State<UserProfile> createState() => _UserProfileState();
}
class _UserProfileState extends State<UserProfile> {
@override
Widget build(BuildContext context) {
final Storage storage = Storage();
return Scaffold(
appBar: AppBar(
title: Text('Profile Picture'),
),
body: Column(
children: [
Center(
child: ElevatedButton(
onPressed: () async {
final results = await FilePicker.platform.pickFiles(
allowMultiple: false,
type: FileType.custom,
allowedExtensions: ['png', 'jpg'],
);
if (results == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No selected file.')));
}
final path = results?.files.single.path;
final fileName = results?.files.single.name;
// when I added this line of code there will be an error when I did not choose any image
storage
.uploadFile(path!, fileName!)
.then((value) => print('done'));
},
child: Text('Upload profile picture')))
],
),
);
}
}
CodePudding user response:
if (results == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No selected file.')));
} else {
final path = results.files.single.path;
final fileName = results.files.single.name;
print(path);
print(fileName);
storage
.uploadFile(path!, fileName)
.then((value) => print('done'));
}
},
CodePudding user response:
To add to Bart's answer: As the error message is currently missing in the question, I can only guess that it has todo with the forced optional unwrapping (!) in this function call
storage
.uploadFile(path!, fileName!)
.then((value) => print('done'));
You should check these values for null before accessing them.