创建默认应用程序时,FirebaseOptions不能为null

dzhpxtsq  于 2022-11-30  发布在  SEO
关注(0)|答案(7)|浏览(214)

我试图尝试在Flutter集成电子邮件和基于谷歌的登录示例项目,并计划使用firebase初始化做它,而我已经按照教程中提到的所有步骤,我得到这个错误,只要firebase试图被初始化。

"FirebaseOptions cannot be null when creating the default app."
    at Object.throw_ [as throw] (http://localhost:7357/dart_sdk.js:5063:11)
    at Object.assertFailed (http://localhost:7357/dart_sdk.js:4988:15)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp (http://localhost:7357/packages/firebase_core_web/firebase_core_web.dart.lib.js:252:42)
    at initializeApp.next (<anonymous>)
    at http://localhost:7357/dart_sdk.js:40192:33
    at _RootZone.runUnary (http://localhost:7357/dart_sdk.js:40062:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:7357/dart_sdk.js:34983:29)
    at handleValueCallback (http://localhost:7357/dart_sdk.js:35551:49)
    at Function._propagateToListeners (http://localhost:7357/dart_sdk.js:35589:17)
    at _Future.new.[_completeWithValue] (http://localhost:7357/dart_sdk.js:35437:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:7357/dart_sdk.js:35458:35)
    at Object._microtaskLoop (http://localhost:7357/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:7357/dart_sdk.js:40336:13)
    at http://localhost:7357/dart_sdk.js:35811:9

下面是我的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.">
  <meta name="google-signin-client_id" content="619218114547-xxxx.apps.googleusercontent.com">
  <!-- 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="signin_example">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">
  
  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>signin_example</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>
    var serviceWorkerVersion = null;
    var scriptLoaded = false;
    function loadMainDartJs() {
      if (scriptLoaded) {
        return;
      }
      scriptLoaded = true;
      var scriptTag = document.createElement('script');
      scriptTag.src = 'main.dart.js';
      scriptTag.type = 'application/javascript';
      document.body.append(scriptTag);
    }

    if ('serviceWorker' in navigator) {
      // Service workers are supported. Use them.
      window.addEventListener('load', function () {
        // Wait for registration to finish before dropping the <script> tag.
        // Otherwise, the browser will load the script multiple times,
        // potentially different versions.
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => {
            function waitForActivation(serviceWorker) {
              serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                }
              });
            }
            if (!reg.active && (reg.installing || reg.waiting)) {
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing || reg.waiting);
            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
            } else {
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            }
          });

        // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plaint <script> tag.
        setTimeout(() => {
          if (!scriptLoaded) {
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          }
        }, 4000);
      });
    } else {
      // Service workers not supported. Just drop the <script> tag.
      loadMainDartJs();
    }
  </script>
  <script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.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
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xxx",
      authDomain: "xxx",
      projectId: "xx",
      storageBucket: "exxx",
      messagingSenderId: "xxx",
      appId: "xxx",
      measurementId: "xxx"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
  </script>
</body>
</html>

firebase初始化发生的main. dart文件中的部分代码

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

项目的pubsec.yaml文件

name: signin_example
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.15.0-268.18.beta <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.3.0
  firebase_core: ^1.10.2
  google_sign_in: ^5.2.1
  shared_preferences: ^2.0.9

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^1.0.0

# The following section is specific to Flutter.
flutter:

  assets:
    - assets/images/

  uses-material-design: true

有谁能帮我弄明白这里的问题是什么吗?

mfpqipee

mfpqipee1#

最新消息:
对于您的firebase_core版本,一旦您在flutter代码中初始化firebase,似乎就足以通过FirebaseOptions(并且您不需要在index.html中使用任何脚本标记):

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    // Replace with actual values
    options: FirebaseOptions(
      apiKey: "XXX",
      appId: "XXX",
      messagingSenderId: "XXX",
      projectId: "XXX",
    ),
  );
  runApp(MyApp());
}

或者,也可以按照更新后的official documentation,使用Firebase CLI在lib文件夹中自动创建一个firebase_options.dart文件,该文件将为您定义正确的FirebaseOptions。步骤如下:
1.安装Flutterfire CLI:

dart pub global activate flutterfire_cli

1.配置Flutterfire(在项目的根目录下运行,并通过向导选择正确的Firebase项目和目标平台):

flutterfire configure

1.将自动生成的firebase_options.dart文件导入main.dart文件,并按如下方式初始化Firebase

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}

上一个答案:
docs
目前将Firebase SDK添加到Flutter Web项目的唯一方法是从Firebase内容交付网络(CDN)导入脚本。
因此,请尝试使用脚本标签导入8.6.1版本的相关firebase组件,如下所示(更多信息here):

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
  <script>
    var firebaseConfig = {
      apiKey: "xxx",
      authDomain: "xxx",
      projectId: "xx",
      storageBucket: "exxx",
      messagingSenderId: "xxx",
      appId: "xxx",
      measurementId: "xxx"
    };

    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
  </script>
f0ofjuux

f0ofjuux2#

为flutter应用添加web功能,我们需要在Firebase.initializeApp(options:FirebaseOptions...)的选项参数中提供值。
这些值是我们在Firebase控制台中添加web应用时得到的。我所做的是在lib文件夹中创建config/config.dart文件。其中:

class Configurations {
      static const _apiKey = "Your values";
      static const _authDomain = "Your values";
      static const _projectId = "Your values";
      static const _storageBucket = "Your values"
      static const _messagingSenderId ="Your values"
      static const _appId = "Your values"
    
//Make some getter functions
      String get apiKey => _apiKey;
      String get authDomain => _authDomain;
      String get projectId => _projectId;
      String get storageBucket => _storageBucket;
      String get messagingSenderId => _messagingSenderId;
      String get appId => _appId;
    }

然后将config文件夹添加到.gitignore

lib/config

现在将文件导入相关部分,然后

import 'config/config.dart';

final configurations = Configurations();
Future<void> init() async {
        await Firebase.initializeApp(
            options: FirebaseOptions(
                apiKey: configurations.apiKey,
                appId: configurations.appId,
                messagingSenderId: configurations.messagingSenderId,
                projectId: configurations.projectId));

现在应该可以了。

hs1rzwqc

hs1rzwqc3#

我也遇到了这个问题。对我有效的修复方法是:
在我的main()中我变了

Future<void> main() async {
  await Firebase.initializeApp();
  runApp(const MyApp());
}

Future<void> main() async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

而现在它对我起作用了!
只需确保已激活flutter cli(参见段落答案)并运行flutterfire configure
完成所有这些操作后,确保生成了lib/firebase_options.dart

6rvt4ljy

6rvt4ljy4#

将此代码添加到main.dart文件和main方法内部

WidgetsFlutterBinding.ensureInitialized();
 if (kIsWeb)
  await Firebase.initializeApp(
  options: FirebaseOptions(
    apiKey: "your key",
    appId: "your key",
    messagingSenderId: "your key",
    projectId: "your key",
  ),
);
else
  await Firebase.initializeApp();
xlpyo6sf

xlpyo6sf5#

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
// Replace with actual values
options: const FirebaseOptions(
  apiKey: "XXX",
  appId: "XXX",
  messagingSenderId: "XXX",
  projectId: "XXX",
),
);

(我的应用程序);}

xvw2m8pv

xvw2m8pv6#

对我有用的东西被改变了

void main() {

void main() async {

把所有东西都倒进去

const firebaseConfig = {
    apiKey: "xx",
    authDomain: "x",
    projectId: "ax",
    storageBucket: "ax",
    messagingSenderId: "x",
    appId: "1xf",
    measurementId: "x"
  };

并将其提供给

Firebase.Initiailaze(options : FirebaseOptions(...))
brgchamk

brgchamk7#

转到你的主. dart文件。添加这一行给我你的应用程序初始化firebase当平台是web

await Firebase.initializeApp(options: FirebaseOptions(
      apiKey: 'AIzaSyDs7889PirDMygOld062sKi0hmnOEVE_tE',
      appId: '1:334819000485:web:5398weew88a23eeb5ae6fb3c',
      messagingSenderId: '334890062485',
      projectId: 'sample-49732',
    ));
  }```
Just below WidgetsFlutterBinding.ensureInitialized() and above

相关问题