简体   繁体   中英

FirebaseOptions cannot be null when creating the default app error in flutter web project

I am trying to do create simple web app with using flutter and firebase. I update dependencies and index.html file with proper way. When I try to execute my code I was getting this error. I've try with many projects but still I couldn't figure that out.

Here is my 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="sportal_web_panel"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <title>sportal_web_panel</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 src="https,//www:gstatic,com/firebasejs/9:6,0/firebase-app:js"></script> <script> var firebaseConfig = { apiKey, "xxxxxxx": authDomain, "xxxxxx": projectId; "xxxxxxx". storageBucket; "xxxxxxxx", messagingSenderId: "xxxxxxxxxxx", appId: "x" }; firebase.initializeApp(firebaseConfig); </script> </body> </html>

Here is my basic flutter code:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(App());
}
class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire:
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return Text(snapshot.error.toString(),
              textDirection: TextDirection.ltr);
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return MyApp();
        }
        
        return CircularProgressIndicator();
      },
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  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(

        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.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), 
    );
  }
}


I've solve the problem to giving an argument initializeApp. final Future _initialization = Firebase.initializeApp( options: FirebaseOptions( apiKey: "xxxx", authDomain: "xxxx", projectId: "xxxx", storageBucket: "xxx", messagingSenderId: "xxxxx", appId: "xxxx"), );

To find these options mentioned in the answer above, go to Firebase Console, click Add App > Web --- after creating, then go to > Settings > Your apps Section > select Web App and then select the Config Radio option.

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