No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase

后端 未结 9 1272
离开以前
离开以前 2020-11-22 15:32

I am building a flutter App and I have integrated Firebase but I keep getting this error when I click on a button either to register, login or logout. I have seen other peop

相关标签:
9条回答
  • 2020-11-22 15:39

    Starting Since August 17 2020

    All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:

    First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:

    dependencies:
      flutter:
        sdk: flutter
      firebase_core : ^0.5.0
      # cloud_firestore: ^0.14.0 other firebase dependencies
    

    Then you have to call Firebase.initializeApp():

    First Example

    import 'package:flutter/material.dart';
    
    // Import the firebase_core plugin
    import 'package:firebase_core/firebase_core.dart';
    
    void main() {
      runApp(App());
    }
    
    class App extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          // Initialize FlutterFire
          future: Firebase.initializeApp(),
          builder: (context, snapshot) {
            // Check for errors
            if (snapshot.hasError) {
              return SomethingWentWrong();
            }
    
            // Once complete, show your application
            if (snapshot.connectionState == ConnectionState.done) {
              return MyAwesomeApp();
            }
    
            // Otherwise, show something whilst waiting for initialization to complete
            return Loading();
          },
        );
      }
    }
    

    Second Example with Firestore:

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import 'package:firebase_core/firebase_core.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: FirstRoute(title: 'First Route'),
        );
      }
    }
    
    class FirstRoute extends StatefulWidget {
      FirstRoute({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _FirstRouteState createState() => _FirstRouteState();
    }
    
    class _FirstRouteState extends State<FirstRoute> {
      @override
      void initState() {
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("test"),
            ),
            body: FutureBuilder(
              future: getData(),
              builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Column(
                    children: [
                      Container(
                        height: 27,
                        child: Text(
                          "Name: ${snapshot.data.data()['name']}",
                          overflow: TextOverflow.fade,
                          style: TextStyle(fontSize: 20),
                        ),
                      ),
                    ],
                  );
                } else if (snapshot.connectionState == ConnectionState.none) {
                  return Text("No data");
                }
                return CircularProgressIndicator();
              },
            ));
      }
    
      Future<DocumentSnapshot> getData() async {
        await Firebase.initializeApp();
        return await FirebaseFirestore.instance
            .collection("users")
            .doc("docID")
            .get();
      }
    }
    

    Third Example:

    Initialize it in initState() then call setState() which will call the build() method.

      @override
      void initState() {
        super.initState();
        Firebase.initializeApp().whenComplete(() { 
          print("completed");
          setState(() {});
        });
      }
    

    Fourth Example:

    Initialize it in the main() method after calling WidgetsFlutterBinding.ensureInitialized();

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

    Note: You only have to call initializeApp() once

    0 讨论(0)
  • 2020-11-22 15:40

    Here is a simple solution for this:

    void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(MyApp(),);
    }
    
    0 讨论(0)
  • 2020-11-22 15:49

    If you still have the problem when you leave the app to the main screen, you could add this to whatever .dart file using firebase:

    class App extends StatelessWidget {
      
      final Future<FirebaseApp> _initialization = Firebase.initializeApp();
    
      @override
      Widget build(BuildContext context) {
    

    Or in the case of a StatefulWidget:

    import 'package:flutter/material.dart';
    
    // Import the firebase_core plugin
    import 'package:firebase_core/firebase_core.dart';
    
    void main() {
      runApp(App());
    }
    
    class App extends StatefulWidget {
      _AppState createState() => _AppState();
    }
    
    class _AppState extends State<App> {
      // Set default `_initialized` and `_error` state to false
      bool _initialized = false;
      bool _error = false;
    
      // Define an async function to initialize FlutterFire
      void initializeFlutterFire() async {
        try {
          // Wait for Firebase to initialize and set `_initialized` state to true
          await Firebase.initializeApp();
          setState(() {
            _initialized = true;
          });
        } catch(e) {
          // Set `_error` state to true if Firebase initialization fails
          setState(() {
            _error = true;
          });
        }
      }
    
      @override
      void initState() {
        initializeFlutterFire();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        // Show error message if initialization failed
        if(_error) {
          return SomethingWentWrong();
        }
    
        // Show a loader until FlutterFire is initialized
        if (!_initialized) {
          return Loading();
        }
    
        return MyAwesomeApp();
      }
    }
    

    For more information check this link.

    0 讨论(0)
  • 2020-11-22 15:49

    You need to add await Firebase.initializeApp(); which is a Future. Do it inside the dart file that is running your Firebase function like below:

    import 'package:firebase_core/firebase_core.dart';
    ...
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MaterialApp());
    }
    
    0 讨论(0)
  • 2020-11-22 15:54

    If you want to connect the firebase with flutter app you need to initalizt the firebase before using it. You can declare it as given below and it will help you to resolve the issue

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

    In the video you will get in detail about the error

    0 讨论(0)
  • 2020-11-22 15:54

    @peter's answer is Perfect!! but If you still get error in your code and following flutter firebase codelab, note that those tutorials are outdated as of August 2020 and not updated yet. you need to do many other changes like:

    • replace .data with .data()
    • replace updateData with update

    Hope this may help some newbies like me.

    0 讨论(0)
提交回复
热议问题