flutter-tutorials icon indicating copy to clipboard operation
flutter-tutorials copied to clipboard

[Question] Where should I initialize FlutterFire?

Open chanlee opened this issue 5 years ago • 2 comments

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 avatar Aug 25 '20 13:08 chanlee

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?

chanlee avatar Aug 26 '20 02:08 chanlee

You initialize in the main function

In your main.dart

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

DEVSOG12 avatar Sep 15 '20 10:09 DEVSOG12