在Flutter Web中初始化auth()时出现“NoSuchMethodError:尝试调用非函数,例如null:'dart.global.firebase.auth'”错误

18

我正在尝试在Flutter Web应用程序中使用Firebase Authentication实现登录功能。 我已经可以在未登录的情况下使用Firestore在同一应用程序中存储/提取数据。

执行应用程序时,它显示错误“NoSuchMethodError:试图调用非函数(例如null):'dart.global.firebase.auth'”

我认为错误是由调用auth()方法引起的。

请问您如何修复它? 或者,Firebase Authentication是否尚未支持Flutter Web??

导入firebase.dart。 https://firebase.google.com/docs/reference/js/firebase

import 'package:firebase/firebase.dart';

使用auth()初始化对象并从参数中调用sign-in方法。

final Auth _auth = auth();

Future<UserCredential> signIn(String email, String password) async {
  final UserCredential user = await _auth.signInAndRetrieveDataWithEmailAndPassword(email, password);
  return user;
}

你是否调试了你的应用程序,以查看你传递给_auth的值是否确实为null?你确定你已经连接到数据库的应用程序,即:app_name没有错误,在应用程序文件夹中有google-services.json。 - Ryk
Ryk,感谢您的评论。实际上,我无法确认_auth是否为null,因为在调用auth()时应用程序崩溃了...有没有办法确认它呢? 是的,我可以从应用程序中使用firestore获取和放置数据。我不使用google-services.json或GoogleService-Info.plist,因为该应用程序是面向Web的。相反,我调用initializeApp()。(https://firebase.google.com/docs/reference/js/firebase#initialize-app) - Hirotaka Nishimiya
你是否使用了来自 pub 的包?如果你使用了来自 pub 的 firebase 包,那么你还需要将 firebase-app.js 插入到你的页面中。我没有在 web 上使用 flutter,所以我不知道在你的应用程序上放置脚本的位置。 - oon arfiandwi
嗯,谢谢。是的,我使用了来自pub的一个包,并且将firebase-app.js插入到我的index.html中。<script src="https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js"></script> - Hirotaka Nishimiya
顺便提一下,我在Reddit上也找到了以下讨论。但是我找不到我的代码和这个代码之间的区别... https://www.reddit.com/r/FlutterDev/comments/ccqgz0/flutter_web_firebase_authentication/ - Hirotaka Nishimiya
4个回答

38

你需要在你的 index.html 文件中也包含此内容:

<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js"></script>

谢谢。这可能是解决方案。我现在无法尝试,但会尝试。 - Hirotaka Nishimiya
3
这让我解决了问题,我插入了这一行代码后我的应用程序开始工作。然后我阅读之前的几行代码,发现有一条提示来自Firebase设置步骤:<!-- TODO: 添加你想要使用的Firebase产品的SDK库 https://firebase.google.com/docs/web/setup#available-libraries --> - Levente Takács
是的。这也为我解决了问题。 - zak

2

在我的情况下,我需要刷新缓存,仅通过R重新加载/热重载Dart并不足够,因此请在Chrome浏览器中按下CTRL+SHIFT+R以清除缓存。


1
这是因为您没有在index.html文件中调用函数,即:authStateChanges。除了添加脚本:<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>,您还需要将import { authStateChanges } from "https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js";添加到Firebase SDK导入部分(<script type="module">...)。请注意,不要删除HTML标签。

0
对于可能也处于我的情况的任何人。我意识到我添加了这行代码 <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script> 两次,所以我删除了其中一个,保存并运行了flutter clean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接