【问题标题】:Is there any way to load image from Firebase to flutter project according to current user UID有没有办法根据当前用户 UID 从 Firebase 加载图像到颤振项目
【发布时间】:2020-12-10 14:40:31
【问题描述】:

我想从我的 Firebase 存储中加载一张图片。我为名为 {users uid}.png 的用户上传了图片,例如个人资料照片。因此,当我进入用户个人资料屏幕时,我想将这些图片从 firebase 上传到当前用户 uid。最好的方法是什么?我有一个异步方法来设置我的用户属性,例如final loggegInUser,我有一个异步方法

void getCurrentUser() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
        print(uid);
      }
    } catch (e) {
      print(e);
    }
  }

这个方法设置我的全局loggedInUser属性然后我想像这样从firebase存储加载图像

CircleAvatar(
                    backgroundColor: Colors.black,
                    backgroundImage: FirebaseImage(
                            'gs://homeparty-68792.appspot.com/user_profile_images/${loggedInUser.uid}.png')
                       ,
                   
                    radius: 100,
                  ),

但是当我加载这个屏幕时,我得到了

ERROR TYPE Exception has occurred. NoSuchMethodError (NoSuchMethodError: The getter 'uid' was called on null. Receiver: null Tried calling: uid)

错误。 getCurrentUser() 方法正常工作,它打印电子邮件和密码,但在构建小部件中它返回 null。为什么会发生这种情况我需要一些帮助???

【问题讨论】:

  • 使用bloc。将getCurrentUser 放入initState
  • 您没有展示代码,但很可能您还不了解期货如何工作或如何根据未来结果构建小部件。
  • 这能回答你的问题吗? What is a Future and how do I use it?
  • 你在哪里打电话getCurrentUser()
  • 我在上面发布的链接解释了如何正确使用期货并等待它们。或者,您在下面得到的答案为您提供了一个简单的出路,因为您将能够同步获得结果。但无论如何,你迟早会需要这个。

标签: firebase flutter dart firebase-authentication


【解决方案1】:

如果您在initState 中调用getCurrentUser(),那么问题是在检索用户之前调用了build()。因此最好的办法是将cloud_firestore升级到版本0.14.0并添加firebase_core : 0.5.0

dependencies:
  flutter:
    sdk: flutter
  firebase_core : ^0.5.0
  firebase_auth : ^0.18.0
  firebase_storage:^4.0.0
  # cloud_firestore: ^0.14.0 not sure if you are using

然后你可以做如下,首先初始化Firebase:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

getCurrentUser()内部:

void getCurrentUser() {
    try {
      final user =  _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
        print(uid);
      }
    } catch (e) {
      print(e);
    }
  }

在新版本中,获取currentUser 不再是异步的,不再需要async/await

一些有用的链接:

No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase

Undefined class 'FirebaseUser'

cloud_firestore 0.14.0 how to use the data method

The getter 'instance' isn't defined for the type 'Firestore'

【讨论】:

  • 我得到'未定义的名称'Firebase'。尝试将名称更正为已定义的名称,或定义名称“我应该导入哪个包我找不到。
  • 你添加了firebase_core吗? firebase_core : ^0.5.0
  • 是的,我在 pubspec.yml 中添加了 firebase_core : ^0.5.0
  • 当根据您的建议更新我的 pubspec.yml 时,我会遇到越来越多的错误。我无法使用 FIrebaseUser anymroe
  • 有什么办法可以等到getCurrentUser方法完成???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2021-04-24
  • 2017-07-08
  • 1970-01-01
  • 2020-02-28
  • 2020-02-06
  • 2021-09-19
相关资源
最近更新 更多