简体   繁体   中英

FirebaseOptions cannot be null when creating the default app in Flutter Web

I ran into the following error:

Launching lib/main.dart on Chrome in debug mode...
This app is linked to the debug service: ws://127.0.0.1:45119/uWRkb_0RvDE%3D/ws
Debug service listening on ws://127.0.0.1:45119/uWRkb_0RvDE=/ws
💪 Running with sound null safety 💪
Connecting to VM Service at ws://127.0.0.1:45119/uWRkb_0RvDE=/ws
Error: Assertion failed:
options != null
"FirebaseOptions cannot be null when creating the default app."
    at Object.throw_ [as throw] (http://localhost:44579/dart_sdk.js:5061:11)
    at Object.assertFailed (http://localhost:44579/dart_sdk.js:4986:15)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:44579/packages/firebase_core_web/firebase_core_web.dart.lib.js:243:42)
    at initializeApp.next (<anonymous>)
    at http://localhost:44579/dart_sdk.js:38640:33
    at _RootZone.runUnary (http://localhost:44579/dart_sdk.js:38511:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:44579/dart_sdk.js:33713:29)
    at handleValueCallback (http://localhost:44579/dart_sdk.js:34265:49)
    at Function._propagateToListeners (http://localhost:44579/dart_sdk.js:34303:17)
    at _Future.new.[_completeWithValue] (http://localhost:44579/dart_sdk.js:34151:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:44579/dart_sdk.js:34172:35)
    at Object._microtaskLoop (http://localhost:44579/dart_sdk.js:38778:13)
    at _startMicrotaskLoop (http://localhost:44579/dart_sdk.js:38784:13)
    at http://localhost:44579/dart_sdk.js:34519:9

The main.dart is:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'screens/main_page.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Application name
      debugShowCheckedModeBanner: false,
      title: 'Diary Book',
      // Application theme data, you can set the colors for the application as
      // you want
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
        primarySwatch: Colors.green,
      ),
      // A widget which will be started on application startup
      home: GetInfo(),
    );
  }
}

class GetInfo extends StatelessWidget {
  const GetInfo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('diaries').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text("Something went wrong");
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Text('Loading');
          }
          return new ListView(
            children: snapshot.data!.docs.map((DocumentSnapshot document) {
              return new ListTile(
                title: Text(document.get('display_name')),
                subtitle: Text(document.get('profession')),
              );
            }).toList(),
          );
        },
      ),
    );
  }
}

The index.html is:

<!DOCTYPE html>
<html>
<head>
  <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="flutter_web_app">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="shortcut icon" type="image/png" href="favicon.png"/>

  <title>flutter_web_app</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }
  </script>
  <script src="main.dart.js" type="application/javascript"></script>
  <script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-auth.js";
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js";
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-storage.js";

    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
  
    // Your web app's Firebase configuration
    const firebaseConfig = {
      apiKey: "AIzaSyDoO8efzrDVveeXvqqrc39D3XiqfsyoKeU",
      authDomain: "diary-app-course-c6663.firebaseapp.com",
      projectId: "diary-app-course-c6663",
      storageBucket: "diary-app-course-c6663.appspot.com",
      messagingSenderId: "1031493909898",
      appId: "1:1031493909898:web:3cd71413645447b67c1c73"
    };
  
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
  </script>  
</body>
</html>

The pubspec.yaml is:

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  cloud_firestore: ^3.1.5
  cupertino_icons: ^0.1.2
  firebase: ^9.0.2
  firebase_auth: ^3.3.4
  firebase_core: ^1.10.6
  firebase_storage: ^10.2.4
  flutter:
    sdk: flutter
  syncfusion_flutter_datepicker: ^19.2.62

dev_dependencies:
  flutter_test:
    sdk: flutter

What is causing the above error

I was also facing the same issue. You have to do the initializeApp with the options.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: const FirebaseOptions(
      apiKey: "AIzaSyDoO8efzrDVveeXvqqrc39D3XiqfsyoKeU",
      authDomain: "diary-app-course-c6663.firebaseapp.com",
      projectId: "diary-app-course-c6663",
      storageBucket: "diary-app-course-c6663.appspot.com",
      messagingSenderId: "1031493909898",
      appId: "1:1031493909898:web:3cd71413645447b67c1c73"
      ),
  );
  runApp(const MyApp());
}

after adding this it started working.

try to replace the minSdkVersion to 21 and above in the android/app/build.gradle, worked for me ^^

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "my.App"
    minSdkVersion 21 //Line to replace usually set to flutter.minSDK...
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM