简体   繁体   中英

'no default app' exception after Firebase has been initialized

I am initializing Firebase with a specific project. I am then passing the resulting FirebaseApp to FirebaseFirestore.instanceOf method. I am using hard coded config values, because eventually this implementation will use multiple projects.

When I try to write to a collection, I get the following exception...

FirebaseException ([core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp())

Here is a minimal reproducible example, with a comment indicating the the line that throws the exception...

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

void main() {
  runApp(const MyApp());
}

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    _asyncInit();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Test App"),
      ),
      body: Container(),
    );
  }

  Future<void> _asyncInit() async {
    var app = await Firebase.initializeApp(
      name: "my-throwaway-project",
      options: const FirebaseOptions(
        apiKey: "AIzaSyBXOxFf_iXaer4tX-sE8eRrh77VftTKZI0",
        appId: "1:980810897373:android:b1a4bcd50cd76712868834",
        messagingSenderId: "980810897311",
        projectId: "my-throwaway-project",
      ),
    );

    var db = FirebaseFirestore.instanceFor(app: app);
    await db.collection("test1").add({"field1":"value1"}); // this line throws the exception
  }
}

Based on the docs, it seems like I am doing everything correctly to initialize, but yet there is still an error.

Normally we initialize firebase on main before runapp.. may be that is the issue..

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