Flutter - Unhandled Exception: [core/duplicate-app]

Viewed 3053

I am building a flutter app with firebase. The firebase services I am using are Realtime database and Authentication. The app is normally starting as usual without throwing any exception, but while I am hot restarting the app, the app freezes throwing the following exception:

Unhandled Exception: [core/duplicate-app] A Firebase App named "db2" already exists

I believe there's something wrong with initializing FirebaseApp. The initialization code in main.dart reads:

WidgetsFlutterBinding.ensureInitialized();
  final FirebaseApp app = await Firebase.initializeApp(
    name: 'db2',

Can somebody help me solve this issue? Thank you!

3 Answers

I have two apps in firebase.One is Android and another one is web . So Initialize firebase instance like this

const firebaseConfig = FirebaseOptions(
apiKey: "AIzaSyA1S7r-kyTOCLWttcf4kC3Qye0s-gl96Ec",
appId: "1:390108250565:web:9821516ca39ba976358bac",
messagingSenderId: "390108250565",
projectId: "doc-appointment-aa751",
);


if(kIsWeb){

 await Firebase.initializeApp(
   options: firebaseConfig,
 );
}else{
   await Firebase.initializeApp();
} 

This is happening since the FirebaseApp that you initialised, persists when you restart your App. Also, in a case where you are initializing an App other than the Default App, you have to name the Firebase App instances for accessing them.

To solve this you have to catch the error that is being thrown at this step. Do something like this:

try {

// you can also assign this app to a FirebaseApp variable
// for example app = await FirebaseApp.initializeApp...

    await Firebase.initializeApp(
      name: 'SecondaryApp',
      options: FirebaseOptions(
        appId: '<appID>',
        apiKey: '<APIKey>',
        messagingSenderId: '<msgSID>',
        projectId: '<projectID>',
        databaseURL: '<dbUrl>/',
      ),
    );
  } on FirebaseException catch (e) {
    if (e.code == 'duplicate-app') {
// you can choose not to do anything here or either 
// In a case where you are assigning the initializer instance to a FirebaseApp variable, // do something like this:
// 
//   app = Firebase.app('SecondaryApp');
//
    } else {
      throw e;
    }
  } catch (e) {
    rethrow;
  }

To explain this, we are catching the error thrown by the existing FirebaseApp with the same name. This solved my issue, I hope it helps you too.

I have solved this problem by adding a name to the initializeApp method:

void main() async {
  await Firebase.initializeApp(
      name: "YourAppName",
      options: FirebaseOptions(
          apiKey: '<apiKey>',
          appId: '<appId>',
          messagingSenderId: '<senderId>',
          projectId: '<projectId>'));

  runApp(MyApp());
}

NOTE: Use Firebase.initializeApp only once in the whole project.

Related