FilledStacks / flutter-tutorials

The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.
MIT License
4.75k stars 1.76k forks source link

[Question] Where should I initialize FlutterFire? #98

Open chanlee opened 4 years ago

chanlee commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

You initialize in the main function

In your main.dart

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