itsource

기본 앱을 생성할 때 FirebaseOptions는 null일 수 없습니다.

mycopycode 2023. 6. 6. 08:21
반응형

기본 앱을 생성할 때 FirebaseOptions는 null일 수 없습니다.

Flutter 통합 이메일 및 Google 기반 로그인에서 샘플 프로젝트를 시도하고 있으며, 자습서에 언급된 모든 단계를 수행하는 동안 파이어베이스 초기화를 사용할 계획입니다. 파이어베이스를 초기화하려고 하면 바로 이 오류가 발생합니다.

"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

여기 제 인덱스입니다.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

여기서 무슨 문제가 있는지 이해하는 것을 도와줄 수 있는 사람이 있습니까?

업데이트:

당신을 위해firebase_core버전은 다음을 통과하기에 충분해 보입니다.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());
}

또는 업데이트된 공식 문서를 따르고 Firebase CLI를 사용하여 자동으로 다음을 생성할 수도 있습니다.firebase_options.dart파일에 저장lib올바른 폴더를 정의합니다.FirebaseOptions널 위해서.단계는 다음과 같습니다.

  1. Floatfire 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());
}

이전 답변:

문서에서:

현재 Float 웹 프로젝트에 Firebase SDK를 추가하는 유일한 방법은 Firebase 콘텐츠 전송 네트워크(CDN)에서 스크립트를 가져오는 것입니다.

따라서 스크립트 태그를 사용하여 버전이 포함된 관련 Firebase 구성 요소를 가져오십시오.8.6.1아래와 같이(자세한 내용은 여기):

  <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>

앱을 띄우기 위해 웹 기능을 추가하고, 우리는 다음의 옵션 인수에 값을 제공해야 합니다.Firebase.initializeApp(options:FirebaseOptions...).

이러한 값은 Firebase 콘솔에 웹 앱을 추가할 때 얻을 수 있습니다.제가 한 일은config/config.dart줄을 지어 들어가다lib폴더를 누릅니다.위치:

 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;
    }

그런 다음 구성 폴더를 추가합니다..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));

이제 작동합니다.

저도 이 문제에 부딪혔습니다.저에게 효과적인 해결책은 다음과 같습니다.

내 안에서main()lib/main.dart나는 변했어요

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

로.

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

그리고 이제 그것은 나에게 효과가 있습니다!

플라우터 CLI가 활성화되었는지 확인하고(파라솔 응답 참조),flutterfire configure.

모든 작업이 완료되면 다음 사항을 확인합니다.lib/firebase_options.dart생성되었습니다.

main.main 파일과 inside 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();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
// Replace with actual values
options: const FirebaseOptions(
  apiKey: "XXX",
  appId: "XXX",
  messagingSenderId: "XXX",
  projectId: "XXX",
),
);

앱 실행(MyApp(); }

나에게 효과가 있었던 것은 바뀌었습니다.

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(...))

main.dart 파일로 이동합니다.플랫폼이 웹 상태일 때 이 줄을 앱에 추가하여 Firebase 초기화

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

저도 제 앱에 같은 문제가 있었습니다.

변경한 내용:

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

다음 대신:

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

언급URL : https://stackoverflow.com/questions/70232931/firebaseoptions-cannot-be-null-when-creating-the-default-app

반응형