我正在构建一个flutter应用程序,我试图将一个图像上传到firebase数据库,但得到一个错误LateInitializationError: Field '_pickedImage' has not been initialized. Error: Unexpected null value.
。我也使用?
操作符检查了空值,但我不知道我错过了什么。
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
class AuthController extends GetxController {
static AuthController instance = Get.find();
late Rx<User?> _user;
late Rx<File?> _pickedImage;
File? get profilePhoto => _pickedImage.value;
User get user => _user.value!;
@override
void onReady() {
super.onReady();
_user = Rx<User?>(firebaseAuth.currentUser);
_user.bindStream(firebaseAuth.authStateChanges());
ever(_user, _setInitialScreen);
}
_setInitialScreen(User? user) {
if (user == null) {
Get.offAll(() => LoginScreen());
} else {
Get.offAll(() => const HomeScreen());
}
}
void pickImage() async {
final pickedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
Get.snackbar('Profile Picture',
'You have successfully selected your profile picture!');
}
_pickedImage = Rx<File?>(File(pickedImage!.path));
}
// upload to firebase storage
Future<String> _uploadToStorage(File image) async {
Reference ref = firebaseStorage
.ref()
.child('profilePics')
.child(firebaseAuth.currentUser!.uid);
UploadTask uploadTask = ref.putFile(image);
TaskSnapshot snap = await uploadTask;
String downloadUrl = await snap.ref.getDownloadURL();
return downloadUrl;
}
}
2条答案
按热度按时间n53p2ov01#
将
late Rx<File?> _pickedImage;
更改为Rxn<File> _pickedImage = Rxn<File>();
Rxn<File>()
相当于Rx<File?>(null)
;sd2nnvve2#
您必须移除最近添加的before _pickImage或必须在init状态下初始化