(Flutter × Firebase)Webアプリだけinitializeが行われない
解決したいこと
iOSやAndroidのエミュレーターだときちんと動くのに、Webアプリだけ画面が真っ白になってしまう。
FlutterとFirebaseを用いたツイッターのようなアプリを作っています。
何かいい解決策を教えていただけると嬉しいです。
発生している問題・エラー
Error: [core/not-initialized] Firebase has not been correctly initialized.
Usually this means you've attempted to use a Firebase service before calling
`Firebase.initializeApp`.
該当するソースコード
main.dart
Future<void> main() async {
await runZonedGuarded(() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load();
// Firebaseがまだ初期化されていない場合のみ、初期化を行う
if (Firebase.apps.isEmpty) {
try {
print("Firebase initializing..."); // ← この行を追加
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
print("Firebase initialized successfully."); // ← この行を追加
} catch (e, stackTrace) {
print('Firebase initialization failed');
print('Error: $e');
print('StackTrace: $stackTrace');
return;
}
}
runApp(const ProviderScope(child: MyApp()));
}, (error, stackTrace) {
if (Firebase.apps.isNotEmpty) {
FirebaseCrashlytics.instance.recordError(error, stackTrace);
} else {
print('Error occurred, but Firebase is not initialized');
print('Error: $error');
print('StackTrace: $stackTrace');
}
});
}
class MyApp extends ConsumerWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
// FirebaseCrashlyticsインスタンスをここで設定します。
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
final User? onceUser = FirebaseAuth.instance.currentUser;
final ThemeModel themeModel = ref.watch(themeProvider);
// FutureBuilderは必要ないため、直接MaterialAppを返します。
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
debugShowCheckedModeBanner: false,
title: appTitle,
theme: themeModel.isDarkTheme
? darkThemeData(context: context)
: lightThemeData(context: context),
home: onceUser == null
? const LoginPage()
: onceUser.emailVerified
? MyHomePage(
themeModel: themeModel,
)
: const VerifyEmailPage(),
);
}
}
class SomethingWentWrong extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Something went wrong!'),
),
);
}
}
class Loading extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
}
class MyHomePage extends ConsumerWidget {
const MyHomePage({Key? key, required this.themeModel}) : super(key: key);
final ThemeModel themeModel;
@override
Widget build(BuildContext context, WidgetRef ref) {
// MainModelが起動し、init()が実行されます
final MainModel mainModel = ref.watch(mainProvider);
final SNSBottomNavigationBarModel snsBottomNavigationBarModel =
ref.watch(snsBottomNavigationBarProvider);
return Scaffold(
body: mainModel.isLoading
? Center(
child: Text(returnL10n(context: context)!.loading),
)
: PageView(
controller: snsBottomNavigationBarModel.pageController,
onPageChanged: (index) =>
snsBottomNavigationBarModel.onPageChanged(index: index),
// childrenの個数はElementsの数
children: [
// 注意:ページじゃないのでScaffold
HomeScreen(
mainModel: mainModel,
themeModel: themeModel,
muteUsersModel: MuteUsersModel(),
),
SearchPage(
mainModel: mainModel,
),
const ArticlesScreen(),
ProfileScreen(
mainModel: mainModel,
),
],
),
bottomNavigationBar: SNSBottomNavigationBar(
snsBottomNavigationBarModel: snsBottomNavigationBarModel),
);
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="udemy_flutter_sns">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>udemy_flutter_sns</title>
<link rel="manifest" href="manifest.json">
<script>
// The value below is injected by flutter build, do not touch.
const serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function(engineInitializer) {
engineInitializer.initializeEngine().then(function(appRunner) {
appRunner.runApp();
});
}
});
});
</script>
</body>
</html>
自分で試したこと
ドキュメントに従って、index.htmlにscriptで囲みながらFirebase関連のSDKとinitializeを追加した→
効果がなかったので再び消した
GitHub
https://github.com/terisuke/FlutterSNS/tree/develop
0