Flutter Web集成firebase_auth时出现JavaScriptObject空值错误
Flutter Web端FirebaseAuth调用抛出类型转换错误解决方案
问题描述
严格遵循Firebase官方配置步骤完成Flutter Web环境搭建,重复操作两次确认无遗漏。Android端运行正常,但Web端调用FirebaseAuth.instance.authStateChanges()时抛出错误:
Expected a value of type 'JavaScriptObject', but got one of type 'Null'.
已尝试新建项目、检查Flutter/Dart版本(flutter doctor无异常),问题仍未解决。
复现代码
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'firebase_options.dart'; import 'package:firebase_auth/firebase_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); FirebaseAuth.instance .authStateChanges() .listen((User? user) { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); } }); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
错误堆栈
Expected a value of type 'JavaScriptObject', but got one of type 'Null'. dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:3 throw_ dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 127:3 castError dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 818:12 cast dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/classes.dart 652:14 as_C dart-sdk/lib/_internal/js_shared/lib/js_util_patch.dart 81:5 getProperty packages/firebase_auth_web/src/interop/auth.dart 314:54 get currentUser packages/firebase_auth_web/firebase_auth_web.dart 167:50 get currentUser packages/firebase_auth_web/firebase_auth_web.dart 264:11 authStateChanges dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 331:40 runBody dart-sdk/lib/async/zone.dart 1661:54 runUnary dart-sdk/lib/async/future_impl.dart 162:18 handleValue dart-sdk/lib/async/future_impl.dart 846:44 handleValueCallback dart-sdk/lib/async/future_impl.dart 875:13 _propagateToListeners dart-sdk/lib/async/future_impl.dart 647:5 _completeWithValue dart-sdk/lib/async/future_impl.dart 721:7 callback dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7 <fn>
解决方案
该错误源于Web端Firebase JS SDK未正确初始化,导致Dart层无法获取到有效的JS auth实例,以下是针对性修复步骤:
1. 检查并修正web/index.html中的Firebase JS配置
确保在web/index.html的<body>标签末尾正确注入Firebase JS SDK,且包含auth模块,配置信息需与DefaultFirebaseOptions完全一致:
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js"; import { getAuth } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js"; const firebaseConfig = { apiKey: "你的API_KEY", authDomain: "你的AUTH_DOMAIN", projectId: "你的PROJECT_ID", storageBucket: "你的STORAGE_BUCKET", messagingSenderId: "你的MESSAGING_SENDER_ID", appId: "你的APP_ID" }; const app = initializeApp(firebaseConfig); // 提前初始化auth实例,确保Dart层调用时已存在 const auth = getAuth(app); </script>
注意:JS SDK版本需与pubspec.yaml中firebase_auth、firebase_core的版本兼容(如firebase_auth: ^4.12.1对应JS SDK 10.x.x系列)。
2. 延迟auth状态监听至Flutter框架初始化完成
Web端Firebase初始化存在微任务延迟,将auth监听逻辑放到runApp之后,用addPostFrameCallback确保框架准备就绪:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); // 等待Flutter框架完成首帧渲染后再监听auth状态 WidgetsBinding.instance.addPostFrameCallback((_) { FirebaseAuth.instance .authStateChanges() .listen((User? user) { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); } }); }); }
3. 统一Firebase依赖版本
确保pubspec.yaml中的Firebase依赖为稳定兼容版本,避免版本不匹配导致的交互错误:
dependencies: flutter: sdk: flutter firebase_core: ^2.24.2 firebase_auth: ^4.12.1
4. 清理缓存并重新构建
执行以下命令清理旧缓存,重新构建Web项目:
flutter clean flutter build web
验证
完成上述步骤后,重新启动Web服务,检查是否仍抛出类型转换错误,若auth状态正常打印则问题解决。
内容的提问来源于stack exchange,提问作者Sebastián Martinez Santos
相关产品推荐
相关产品推荐

