Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Where should I initialize FlutterFire? #98

Open
chanlee opened this issue Aug 25, 2020 · 2 comments
Open

[Question] Where should I initialize FlutterFire? #98

chanlee opened this issue Aug 25, 2020 · 2 comments

Comments

@chanlee
Copy link

chanlee commented Aug 25, 2020

FlutterFire overview page is saying that "await Firebase.initializeApp();" is needed.
(https://firebase.flutter.dev/docs/overview)

How should I can to do that is properly in stacked framework?

@chanlee
Copy link
Author

chanlee commented Aug 26, 2020

I applied it as below.

import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:injectable/injectable.dart';

import '../models/test_model.dart';

@singleton
class FirestoreService {
  bool _initialized = false;

  // Define an async function to initialize FlutterFire
  Future<void> initializeFlutterFire() async {
    try {
      // Wait for Firebase to initialize and set `_initialized` state to true
      await Firebase.initializeApp();
      _initialized = true;
    } catch (e) {
      // Set `_error` state to true if Firebase initialization fails
      print('error occured');
    }
  }

  Future<CountryModel> getCountryData() async {
    if (!_initialized) {
      await initializeFlutterFire();
    }

    CollectionReference example =
        FirebaseFirestore.instance.collection('example');
    DocumentSnapshot doc = await country.doc('test').get();
    return TestModel.fromJson(doc.data());
  }
}

It works!
Is there any room for improvement or fixing?

@DEVSOG12
Copy link

You initialize in the main function

In your main.dart

void main(){ setupLocator(); await initializeFlutterFire(); runApp(child:MyApp()); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants