Open chanlee opened 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?
You initialize in the main function
In your main.dart
void main(){ setupLocator(); await initializeFlutterFire(); runApp(child:MyApp()); }
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?