简体   繁体   English

在向 email 注册时将用户头像图像上传到 firebase 时,在使用 getter 获取 ImageUrl 时会给出 null 值

[英]While uploading user avatar image to firebase while registering with email gives null value when using getter to get ImageUrl

So I am trying to upload user avatar to firebase storage while registering to firebase auth with email and password and simultaneously adding it to cloud firestore, but the image I upload using imageFilePicker returns null when trying to get it. So I am trying to upload user avatar to firebase storage while registering to firebase auth with email and password and simultaneously adding it to cloud firestore, but the image I upload using imageFilePicker returns null when trying to get it. I am using provider for state management.我正在使用提供程序进行 state 管理。 I am new to this.我是新来的。

Image Upload code:图片上传代码:

class FirebaseOperations with ChangeNotifier {
 UploadTask imageUploadTask;
 String initUserEmail, initUserName, initUserImage;
 String get getInitUserName => initUserName;
 String get getInitUserEmail => initUserEmail;
 String get getInitUserImage => initUserImage;

 Future uploadUserAvatar(BuildContext context) async {
Reference imageReference = FirebaseStorage.instance
    .ref()
    .child('userProfileAvatar/${DateTime.now()}');
imageUploadTask = imageReference.putFile(
    Provider.of<ImageSelect>(context, listen: false).getUserAvatar);
await imageUploadTask.whenComplete(() {
  print('Image uploaded!');
});
imageReference.getDownloadURL().then((url) {
  print("################################################" + url);
  Provider.of<ImageSelect>(context, listen: false).userAvatarUrl =
      url.toString();
  print(
      'the user profile avatar url => ${Provider.of<ImageSelect>(context, listen: false).userAvatarUrl}');
  notifyListeners();
});
}
 Future initUserData(BuildContext context) async {
   return FirebaseFirestore.instance
    .collection('users')
    .doc(Provider.of<Authentication>(context, listen: false).getUserUid)
    .get()
    .then((doc) {
  print('Fetching user data');

  initUserName = doc.data()['username'];
  initUserEmail = doc.data()['useremail'];
  initUserImage = doc.data()['userimage'];
  print(initUserName);
  print(initUserEmail);
  print(initUserImage);
  notifyListeners();
});
}
}  

Image select code:图片 select 代码:

class ImageSelect with ChangeNotifier {
final picker = ImagePicker();
File userAvatar;
File get getUserAvatar => userAvatar;
String userAvatarUrl;
String get getUserAvatarUrl => userAvatarUrl;

Future pickUserAvatar(BuildContext context, ImageSource source) async {
final pickedUserAvatar = await picker.getImage(source: source);
pickedUserAvatar == null
    ? print('Select image')
    : userAvatar = File(pickedUserAvatar.path);
// print(userAvatar.path);
if (userAvatar != null) {
  await Provider.of<FirebaseOperations>(context, listen: false)
      .uploadUserAvatar(context);
} else
  print('Image not Selected ');
notifyListeners();
}

Register Button code:注册按钮代码:

GestureDetector(
            onTap: () {
              if (_emailController.text.isNotEmpty) {
                Provider.of<Authentication>(context, listen: false)
                    .createAccount(
                        _emailController.text, _passwordController.text)
                    .whenComplete(() {
                 
                  print('Creating collection...');
                  Provider.of<FirebaseOperations>(context, listen: false)
                      .createUserCollection(context, {
                    'userpassword': _passwordController.text,
                    'useruid':
                        Provider.of<Authentication>(context, listen: false)
                            .getUserUid,
                    'useremail': _emailController.text,
                    'username': _fullNameController.text,
                    'usermobile': _phoneNumberController.text,
                    'userimage':
                        Provider.of<ImageSelect>(context, listen: true)
                            .getUserAvatarUrl,
                  });
                }).whenComplete(() {
                  Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                          builder: (context) => HomeScreen()));
                });
              } else {
                warningText(context, 'Fill all the data!');
              }
            },

Error Code:错误代码:

I/flutter (30433): Image uploaded!
I/flutter (30433): 
################################################https://firebasestorage.googleapis.com/v0/b/bubblez-        
e2801.appspot.com/o/userProfileAvatar%2F2021-03-25%2011%3A34%3A39.688986?alt=media&token=78a2be55- 
b45c-453e-a398-02a363178d9d
E/flutter (30433): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a 
deactivated widget's ancestor is unsafe.
E/flutter (30433): At this point the state of the widget's element tree is no longer stable.
E/flutter (30433): To safely refer to a widget's ancestor in its dispose() method, save a reference 
to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's 
didChangeDependencies() method.
E/flutter (30433): #0      Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
package:flutter/…/widgets/framework.dart:3864
E/flutter (30433): #1      Element._debugCheckStateIsActiveForAncestorLookup
 package:flutter/…/widgets/framework.dart:3878
E/flutter (30433): #2      Element.getElementForInheritedWidgetOfExactType
package:flutter/…/widgets/framework.dart:3905
E/flutter (30433): #3      Provider._inheritedElementOf
package:provider/src/provider.dart:327
E/flutter (30433): #4      Provider.of
package:provider/src/provider.dart:284
E/flutter (30433): #5      FirebaseOperations.uploadUserAvatar.<anonymous closure>
package:bubblez/…/authMethods/FirebaseOperations.dart:27
E/flutter (30433): #6      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (30433): #7      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (30433): #8      _FutureListener.handleValue (dart:async/future_impl.dart:152:18)
E/flutter (30433): #9      Future._propagateToListeners.handleValueCallback 
(dart:async/future_impl.dart:704:45)
E/flutter (30433): #10     Future._propagateToListeners (dart:async/future_impl.dart:733:32)
E/flutter (30433): #11     Future._completeWithValue (dart:async/future_impl.dart:539:5)
E/flutter (30433): #12     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:254:13)
E/flutter (30433): #13     MethodChannelReference.getDownloadURL 
(package:firebase_storage_platform_interface/src/method_channel/method_channel_reference.dart)
package:firebase_storage_platform_interface/…/method_channel/method_channel_reference.dart:1
E/flutter (30433): <asynchronous suspension>
E/flutter (30433):

I/flutter (30433): Fetching user data
E/flutter (30433): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: 
NoSuchMethodError: The method '[]' was called on null.
E/flutter (30433): Receiver: null
 E/flutter (30433): Tried calling: []("username")
 E/flutter (30433): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (30433): #1      FirebaseOperations.initUserData.<anonymous closure>
package:bubblez/…/authMethods/FirebaseOperations.dart:50
E/flutter (30433): #2      _rootRunUnary (dart:async/zone.dart:1362:47)

Your problem is in this function你的问题出在这个 function

Future initUserData(BuildContext context) async {
   return FirebaseFirestore.instance
    .collection('users')
    .doc(Provider.of<Authentication>(context, listen: false).getUserUid)
    .get()
    .then((doc) {
  print('Fetching user data')});}

Because in your debug console, I read the line saying Image uploaded!因为在您的调试控制台中,我读到了Image uploaded! , can you confirm that an Image URL and username have been posted to firestore? ,您能否确认图像 URL 和用户名已发布到 Firestore?

Try changing it to this:尝试将其更改为:

 Future initUserData(BuildContext context) async {
  return await FirebaseFirestore.instance //<=== adding await here
 .collection('users')
 .doc(Provider.of<Authentication>(context, listen: false).getUserUid)
 .get()
 .then((doc) {
  initUserName = doc.data()['username'];
  initUserEmail = doc.data()['useremail'];
  initUserImage = doc.data()['userimage'];
  print(initUserName);
  print(initUserEmail);
  print(initUserImage);
  notifyListeners();
});
}

And update on what happens.并更新发生了什么。 Because your error log also says that ['username'] was called on null, which is only the first one of your inquires, it's not reaching the point to image or email.因为您的错误日志还显示在 null 上调用了 ['username'],这只是您的第一个查询,所以它没有到达图像或 email 的位置。

If this doesn't work, we can try working with the BuildContext that is being passed to your provider functions.如果这不起作用,我们可以尝试使用传递给您的提供程序函数的 BuildContext。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将图像上传到Firebase时存在异常 - StorageException while uploading image to Firebase 用户登录后,来自Firebase数据库的评论电子邮件为空 - Email for a comment from Firebase database is null while the user is signed in 上传到firebase时如何压缩图像? - How to compress image while uploading to the firebase? Firebase应用程序在上传图像时崩溃 - Firebase app crash while uploading image 通过EXPO Image Picker上传到Firebase时,使用XMLHttpRequest进行本机响应时,文件图像大小会增加 - File Image size increases while uploading to firebase through expo image picker react native using XMLHttpRequest 在 firebase 中评估当前用户时,null 不是 object - null is not an object while evaluating current user in firebase 向Firebase注册用户时出错 - Error when Registering User with Firebase 当用户使用Firebase电子邮件身份验证进行注册时,能否获取用户设备详细信息并将其保存在数据库中? - Is it possible to get and save the user device detail in the database while the user sign up with Firebase email auth? 使用 Firebase Cloud Functions 将文件上传到 Firebase 存储时出错 - Error while uploading file to Firebase Storage using Firebase Cloud Functions 使用react-native-fetch-blob将图像上传到React Native中的Firebase存储时出错 - getting error while uploading image to firebase storage in React Native using react-native-fetch-blob
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM