Related
I am trying to run my app and it is giving the following error
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I have already called firebase.initializeApp() but still the error is same.
here is my code of main file
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => AppointmentsProvider(),
child: MaterialApp(
title: 'Car Wash App',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FutureBuilder(
future: Firebase.initializeApp(),
builder: (ctx, snap) =>
snap.connectionState == ConnectionState.waiting
? Center(
child: Text('Loading...'),
)
: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (ctx, snapShot) =>
snapShot.hasData ? HomePage() : UserAuth(),
),
),
routes: {
HomePage.routeName: (_) => HomePage(),
HistoryPage.routeName: (_) => HistoryPage(),
MyAppointments.routeName: (_) => MyAppointments(),
PackagesPage.routeName: (_) => PackagesPage(),
VehicleType.routeName: (_) => VehicleType(),
SlotPage.routeName: (_) => SlotPage(),
ExtraServicesPage.routeName: (_) => ExtraServicesPage(),
SummaryPage.routeName: (_) => SummaryPage(),
DetailedScreen.routeName: (_) => DetailedScreen(),
PaymentMethodScreen.routeName: (_) => PaymentMethodScreen(),
},
),
);
}
}
Any kind of help is much appreciated. Thank you
You should initialise it in main().
For example:
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}
This link might be helpful for you.
EDIT: The first link has been archived. This is new way to setup firebase in a Flutter project. Steps are pretty same. Last link contains one more step to configure firebase plugins.
Steps are:
Step 1: Install the required command line tools
Step 2: Configure your apps to use Firebase
Step 3: Initialize Firebase in your app
Step 4: Add Firebase plugin
If the above answers don't help, you can solve the problem by following steps:
delete the project and take backup of lib folder and pubspec.yaml file.
Create a new project with the same name
copy backed up files to the newly created project.
run flutter pub get
you are good to go
It literally solved my problem. I hope this will help.
Firebase.initializeApp() is an asynchronous function. You should use "await" to ensure Firebase initialization. And use WidgetsFlutterBinding.ensureInitialized() to prevent flutter errors.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
The problem is that you have configure firebase in your flutter project but you have not initialized it before the app starts.
You need to initialize the firebase sdk asynchronously. This is how to go about it.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
This error is know to occur when you fail to add the required dependencies in both your android side of things in project and app level build.gradle files
Check your android/build.gradle file.
Inside dependecies add
classpath 'com.google.gms:google-services:4.3.14' (use latest version)
Go to app/build.gradle file.
Add the plugin outside dependencies
apply plugin: 'com.google.gms.google-services'
1. Install this package
For installing the Firebase core package Click here
In your main.dart:-
2. Import Firebase_core package :
import 'package:firebase_core/firebase_core.dart';
3. Add these lines in your main :
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(myApp());
}
It worked for me hoping helpful for others too.
I am using below dependencies in my flutter web app with firebaseAuth and firestore:
firebase_core: ^1.7.0
firebase_auth: ^3.1.3
cloud_firestore: ^2.5.3
Below are the script versions on web/index.html:
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
I want to navigate the screen to screen after user login with the credentials. I am tiring below method but its not working. Unable to use then FirebaseAuth.instance.currentUser!.then((user) { and .getDocuments() .where('uid', isEqualTo: user.uid).getDocuments() How to solve this.
Actually, I want to open the admin screen after get the user role saved in firestore user data. So in this case, User id of current user which is logged in should be match to uid field in a document stored in firestore. And then it should be match the role with the role field. For reference please find the images.
I am trying below code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:webfire/admin_screen.dart';
import 'package:webfire/home_screen.dart';
import 'package:flutter/widgets.dart';
class UserManagement {
signOut() {
FirebaseAuth.instance.signOut();
}
//FirebaseFirestore firestore = FirebaseFirestore.instance;
authorizeAdmin(BuildContext context) {
FirebaseAuth.instance.currentUser!.then((user) {
FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: user.uid)
.getDocuments()
.then((docs) {
if (docs.documents[0].exists) {
if (docs.documents[0].data['role'] == 'admin') {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const AdminScreen()));
} else if (docs.documents[0].data['role'] == 'user') {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const HomeScreen()));
}
}
});
});
}
}
Below is Cloud Firestore data Image:
I am using email and password authentication. User id and the uid in firestore are same. you can find below image.
FirebaseAuth.instance.currentUser is no longer Future<User> it's direct User? object
After where condition use .get() function to get Snapshot
I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem?
This is an excerpt of my code
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Center(
child: Container(
child: RaisedButton(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
LoginScreen()));
});
},
child: Text("Logout"),
)
)
)
);
}
}
Below is the thrown exception
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24 _invoke1 (dart:ui/hooks.dart:267:10)
#25 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer:
TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Starting Since August 17 2020
All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:
First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
firebase_core : ^0.5.0
# cloud_firestore: ^0.14.0 other firebase dependencies
Then you have to call Firebase.initializeApp():
First Example
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return SomethingWentWrong();
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return MyAwesomeApp();
}
// Otherwise, show something whilst waiting for initialization to complete
return Loading();
},
);
}
}
Second Example with Firestore:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstRoute(title: 'First Route'),
);
}
}
class FirstRoute extends StatefulWidget {
FirstRoute({Key key, this.title}) : super(key: key);
final String title;
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("test"),
),
body: FutureBuilder(
future: getData(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
children: [
Container(
height: 27,
child: Text(
"Name: ${snapshot.data.data()['name']}",
overflow: TextOverflow.fade,
style: TextStyle(fontSize: 20),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
));
}
Future<DocumentSnapshot> getData() async {
await Firebase.initializeApp();
return await FirebaseFirestore.instance
.collection("users")
.doc("docID")
.get();
}
}
Third Example:
Initialize it in initState() then call setState() which will call the build() method.
#override
void initState() {
super.initState();
Firebase.initializeApp().whenComplete(() {
print("completed");
setState(() {});
});
}
Fourth Example:
Initialize it in the main() method after calling WidgetsFlutterBinding.ensureInitialized();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Note: You only have to call initializeApp() once
Add to pubspec.yaml
firebase_core :
add to main.dart
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
If you followed Peter's answer and are still getting the same error, check to make sure anything else you have in your main function comes after the await Firebase.initializeApp() call, like so:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(MyApp());
}
Since August 2017, all Firebase services have been updated so that you have to call Firebase.initializeApp() in your main before you can use any of the Firebase products, for example:
If you want to use the firebase_core plugin in a flutter application, then in your pubspec.yaml file add the firebase_core as below
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.19.1
Then call the Firebase.initializeApp(): in your app. same as something below:
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Dart-only initialization (Recommended)
Initialize Firebase on all platforms using CLI.
No need to add any native code.
No need to download any Google services file.
Install FlutterFire CLI
dart pub global activate flutterfire_cli
(Optional) Add the following line to your ~/.zshrc file and save it
export PATH="$PATH":"$HOME/.pub-cache/bin"
Run the configure:
flutterfire configure
Press enter to configure all the platforms
You should now have a lib/firebase_options.dart file. Import this file in your main.dart and use Firebase.initializeApp.
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// This is the last thing you need to add.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(...);
}
Migrating to Dart-only initialization:
If you already have an existing application, you can migrate it in the following ways.
Android:
Delete google-services.json file from <flutter-project>/android/app:
Delete the following line in <flutter-project>/android/build.gradle file
Delete the following line in <flutter-project>/android/app/build.gradle file
iOS
Open <flutter-project>/ios/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
macOS
Open <flutter-project>/macos/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
More information can be found here
First, add this dependency:
firebase_core :
Second: in the project main function, add these two lines and make the function async:
void main() async {
// These two lines
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//
runApp(MyApp());
}
Now you can use Firebase normally in any file or widget in the project.
The FutureBuilder widget will work either, but you must add it every time you want to access Firebase.
Peter's answer is perfect!! But if you still get an error in your code and following the Flutter Firebase codelab, note that those tutorials are outdated as of August 2020 and not updated yet.
You need to do many other changes like:
replace .data with .data()
replace updateData with update
Flutter Web with Firebase
If you are using Flutter Web with Firebase make sure you have the SDKs installed in the body tag of your ./web/index.html
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>
Furthermore, make sure you call firebase.initializeApp(...) with the configuration parameters in the index.html as well.
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIz...",
authDomain: "...",
databaseURL: "https://<project-name>.firebaseio.com",
projectId: "...",
storageBucket: "<project-name>.appspot.com",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
At last configure firebase as described in Peter Haddad's answer:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Since Flutter versions 2.8, FlutterFire can now be initialized from Dart on all platforms using the Firebase.initializeApp function. There's a more simple and quicker way to initialize a firebase project, instead of downloading the .json and .plist file from the firebase console and placing them into your Flutter project folders which can result in several warnings. This is a problem I've experienced several times and here's how I solved it.
After creating your project in the firebase console steps here and installed the Firebase CLI here, please proceed with the following steps:
You can skip step 1 and jump to step 4 if you've already configured your firebase project with flutterfire configure.
From your project root terminal, command:
$ flutterfire configure
// This requires the Firebase CLI to work.
Select firebase project by hitting return or enter.
insert the bundle ID. You can get this by right clicking the ios folder > then click'Open in xcode'. The Bundle Identifier will appear in the right white panel and you'll have to type this in the terminal manually when prompted.
** Proceed to step 5 if you already have the firebase_core plugin installed. **
Install the latest version of the firebase_core plugin by running this command from your project root directory:
$ flutter pub add firebase_core // Adds to pubspec.yaml
Add imports to the main file:
import 'package:firebase_core/firebase_core.dart'; //
import 'firebase_options.dart'; // Generated file
Update your main function to initialize firebase with this async function:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform);
runApp(const YourAppName());
}
See the FlutterFire documentation for more information.
You need to add await Firebase.initializeApp(); which is a Future. Do it inside the dart file that is running your Firebase function like below:
import 'package:firebase_core/firebase_core.dart';
...
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp());
}
If you still have the problem when you leave the app to the main screen, you could add this to whatever .dart file using Firebase:
class App extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
Or in the case of a StatefulWidget:
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// Set default `_initialized` and `_error` state to false
bool _initialized = false;
bool _error = false;
// Define an async function to initialize FlutterFire
void initializeFlutterFire() async {
try {
// Wait for Firebase to initialize and set `_initialized` state to true
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch(e) {
// Set `_error` state to true if Firebase initialization fails
setState(() {
_error = true;
});
}
}
#override
void initState() {
initializeFlutterFire();
super.initState();
}
#override
Widget build(BuildContext context) {
// Show error message if initialization failed
if(_error) {
return SomethingWentWrong();
}
// Show a loader until FlutterFire is initialized
if (!_initialized) {
return Loading();
}
return MyAwesomeApp();
}
}
For more information, check this link.
This is the way to initialize firebase in 2022
First of all, Install FlutterFire with this link ==>
Flutter Fire Installation Link
After installing FlutterFire, you'll need to add these lines of code in your lib/main.dart file
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Then edit your Main Function as done below
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform,);
runApp(MyApp());
}
This can change in the future, so refer to this link for the latest implementation reference below
Initializing FlutterFire#
In most cases this problem is observed after upgrading the project from older Flutter version to null safety. These things should be checked:
Ensure you have firebase-core in pubscpec.yaml
Import firebase core:
import 'package:firebase_core/firebase_core.dart';
Init Firebase before any call - preferably inside main.dart so it is executed before any other implementation:
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
From offical documentation.
I needed to reconfigure the Firebase app with FlutterFire cli.
https://firebase.flutter.dev/docs/cli
Install firebase-tool via NPM: npm install -g firebase-tools
Install flutterfire cli: dart pub global activate flutterfire_cli
Run this command to configure firebase in your project: flutterfire configure
Follow the above link and initialise as follows:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
As its await call, The app will show splash screen and Firebase may not initialise so I proceeded next with another FutureBuilder for home screen to make sure Firebase app is initialised before I use FirebaseAuth.
home: FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString(),
style: TextStyle(fontSize: 10));
}
if (snapshot.connectionState == ConnectionState.done) {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
return snapshot.hasData ? Home() : AuthPage();
},
);
} else {
return Text('');
}
})
You can initialize in the main.dart file as well like this using FutureBuilder.
future: Firebase.initializeApp(),
Look at this example.
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'NEWSAPI.org',
home: SplashScreen(),
routes: <String, WidgetBuilder>{
SPLASH_SCREEN: (BuildContext context) => SplashScreen(),
},);
},
);
}
}
you neeed to add await FirebaseApp.initializeApp() in main function remember to add await in main function
On my case, I added web support to my existing project.
The one thing which solved the issue is,
In the web/index.html file
Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0
Snippet
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
<script>
var firebaseConfig = {
....
}
If you are working on a project in which the firebase_core was preconfigured and then you are trying to add new packages it will give that error.
You have to first remove firebase_core: from pubsec.yaml and then save the file and reconfigure it through flutter pub add firebase_core and then flutterfire configure.
Then you can add any new packages.
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
Make sure you are using the right/official version of the firebase package.
I was using:
firebase_core_dart: <version-number>
at: https://pub.dev/packages/firebase_core_dart
instead of the official
firebase_core: <version-number>
at https://pub.dev/packages/firebase_core
Using the first option, I got the initialized when using:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
).whenComplete(
() => print('FIREBASE INITIALIZED================>'));
but the authentication failed with the error message described by the OP.
Try the below code. It will resolve the issue for both IOS and Android.
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isIOS) {
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "found in your google service-info.plist",
appId: "found in your google service-info.plist",
messagingSenderId: "found in firebase",
projectId: "found in firebase"),
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}
For Flutter Users
If you've set Firebase correctly, do not forget to add
await
before
Firebase.initializeApp();
That is mainly the problem with that Exception.
And since it's a Future, do this:
Future<void> main() async {
await Firebase.initializeApp();
In my case it was because for the Web version you have to manually add stuff in the index.html file, not only the .js dependency, but the configuration. See Web Installation.
We tend to forget that for most stuff Flutter is compiled to the target without the need to change anything target-specific, but in this case one must add the configuration for each target.
Use This for flutter :
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.getAnalytics(app);
Instead of this
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
I wanted to comment. But this issue have lot of trails.
For my case.
I was initializing Injection Container Before Firebase.
Hierarchy needs to be check.
Hive.init(directory.path);
await Firebase.initializeApp();// before
await di.init();
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
like this
The problem for me was I initialized it without "await":
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
The correct way is:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem?
This is an excerpt of my code
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Center(
child: Container(
child: RaisedButton(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
LoginScreen()));
});
},
child: Text("Logout"),
)
)
)
);
}
}
Below is the thrown exception
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24 _invoke1 (dart:ui/hooks.dart:267:10)
#25 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer:
TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Starting Since August 17 2020
All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:
First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
firebase_core : ^0.5.0
# cloud_firestore: ^0.14.0 other firebase dependencies
Then you have to call Firebase.initializeApp():
First Example
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return SomethingWentWrong();
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return MyAwesomeApp();
}
// Otherwise, show something whilst waiting for initialization to complete
return Loading();
},
);
}
}
Second Example with Firestore:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstRoute(title: 'First Route'),
);
}
}
class FirstRoute extends StatefulWidget {
FirstRoute({Key key, this.title}) : super(key: key);
final String title;
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("test"),
),
body: FutureBuilder(
future: getData(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
children: [
Container(
height: 27,
child: Text(
"Name: ${snapshot.data.data()['name']}",
overflow: TextOverflow.fade,
style: TextStyle(fontSize: 20),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
));
}
Future<DocumentSnapshot> getData() async {
await Firebase.initializeApp();
return await FirebaseFirestore.instance
.collection("users")
.doc("docID")
.get();
}
}
Third Example:
Initialize it in initState() then call setState() which will call the build() method.
#override
void initState() {
super.initState();
Firebase.initializeApp().whenComplete(() {
print("completed");
setState(() {});
});
}
Fourth Example:
Initialize it in the main() method after calling WidgetsFlutterBinding.ensureInitialized();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Note: You only have to call initializeApp() once
Add to pubspec.yaml
firebase_core :
add to main.dart
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
If you followed Peter's answer and are still getting the same error, check to make sure anything else you have in your main function comes after the await Firebase.initializeApp() call, like so:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(MyApp());
}
Since August 2017, all Firebase services have been updated so that you have to call Firebase.initializeApp() in your main before you can use any of the Firebase products, for example:
If you want to use the firebase_core plugin in a flutter application, then in your pubspec.yaml file add the firebase_core as below
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.19.1
Then call the Firebase.initializeApp(): in your app. same as something below:
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Dart-only initialization (Recommended)
Initialize Firebase on all platforms using CLI.
No need to add any native code.
No need to download any Google services file.
Install FlutterFire CLI
dart pub global activate flutterfire_cli
(Optional) Add the following line to your ~/.zshrc file and save it
export PATH="$PATH":"$HOME/.pub-cache/bin"
Run the configure:
flutterfire configure
Press enter to configure all the platforms
You should now have a lib/firebase_options.dart file. Import this file in your main.dart and use Firebase.initializeApp.
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// This is the last thing you need to add.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(...);
}
Migrating to Dart-only initialization:
If you already have an existing application, you can migrate it in the following ways.
Android:
Delete google-services.json file from <flutter-project>/android/app:
Delete the following line in <flutter-project>/android/build.gradle file
Delete the following line in <flutter-project>/android/app/build.gradle file
iOS
Open <flutter-project>/ios/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
macOS
Open <flutter-project>/macos/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
More information can be found here
First, add this dependency:
firebase_core :
Second: in the project main function, add these two lines and make the function async:
void main() async {
// These two lines
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//
runApp(MyApp());
}
Now you can use Firebase normally in any file or widget in the project.
The FutureBuilder widget will work either, but you must add it every time you want to access Firebase.
Peter's answer is perfect!! But if you still get an error in your code and following the Flutter Firebase codelab, note that those tutorials are outdated as of August 2020 and not updated yet.
You need to do many other changes like:
replace .data with .data()
replace updateData with update
Flutter Web with Firebase
If you are using Flutter Web with Firebase make sure you have the SDKs installed in the body tag of your ./web/index.html
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>
Furthermore, make sure you call firebase.initializeApp(...) with the configuration parameters in the index.html as well.
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIz...",
authDomain: "...",
databaseURL: "https://<project-name>.firebaseio.com",
projectId: "...",
storageBucket: "<project-name>.appspot.com",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
At last configure firebase as described in Peter Haddad's answer:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Since Flutter versions 2.8, FlutterFire can now be initialized from Dart on all platforms using the Firebase.initializeApp function. There's a more simple and quicker way to initialize a firebase project, instead of downloading the .json and .plist file from the firebase console and placing them into your Flutter project folders which can result in several warnings. This is a problem I've experienced several times and here's how I solved it.
After creating your project in the firebase console steps here and installed the Firebase CLI here, please proceed with the following steps:
You can skip step 1 and jump to step 4 if you've already configured your firebase project with flutterfire configure.
From your project root terminal, command:
$ flutterfire configure
// This requires the Firebase CLI to work.
Select firebase project by hitting return or enter.
insert the bundle ID. You can get this by right clicking the ios folder > then click'Open in xcode'. The Bundle Identifier will appear in the right white panel and you'll have to type this in the terminal manually when prompted.
** Proceed to step 5 if you already have the firebase_core plugin installed. **
Install the latest version of the firebase_core plugin by running this command from your project root directory:
$ flutter pub add firebase_core // Adds to pubspec.yaml
Add imports to the main file:
import 'package:firebase_core/firebase_core.dart'; //
import 'firebase_options.dart'; // Generated file
Update your main function to initialize firebase with this async function:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform);
runApp(const YourAppName());
}
See the FlutterFire documentation for more information.
You need to add await Firebase.initializeApp(); which is a Future. Do it inside the dart file that is running your Firebase function like below:
import 'package:firebase_core/firebase_core.dart';
...
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp());
}
If you still have the problem when you leave the app to the main screen, you could add this to whatever .dart file using Firebase:
class App extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
Or in the case of a StatefulWidget:
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// Set default `_initialized` and `_error` state to false
bool _initialized = false;
bool _error = false;
// Define an async function to initialize FlutterFire
void initializeFlutterFire() async {
try {
// Wait for Firebase to initialize and set `_initialized` state to true
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch(e) {
// Set `_error` state to true if Firebase initialization fails
setState(() {
_error = true;
});
}
}
#override
void initState() {
initializeFlutterFire();
super.initState();
}
#override
Widget build(BuildContext context) {
// Show error message if initialization failed
if(_error) {
return SomethingWentWrong();
}
// Show a loader until FlutterFire is initialized
if (!_initialized) {
return Loading();
}
return MyAwesomeApp();
}
}
For more information, check this link.
This is the way to initialize firebase in 2022
First of all, Install FlutterFire with this link ==>
Flutter Fire Installation Link
After installing FlutterFire, you'll need to add these lines of code in your lib/main.dart file
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Then edit your Main Function as done below
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform,);
runApp(MyApp());
}
This can change in the future, so refer to this link for the latest implementation reference below
Initializing FlutterFire#
In most cases this problem is observed after upgrading the project from older Flutter version to null safety. These things should be checked:
Ensure you have firebase-core in pubscpec.yaml
Import firebase core:
import 'package:firebase_core/firebase_core.dart';
Init Firebase before any call - preferably inside main.dart so it is executed before any other implementation:
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
From offical documentation.
I needed to reconfigure the Firebase app with FlutterFire cli.
https://firebase.flutter.dev/docs/cli
Install firebase-tool via NPM: npm install -g firebase-tools
Install flutterfire cli: dart pub global activate flutterfire_cli
Run this command to configure firebase in your project: flutterfire configure
Follow the above link and initialise as follows:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
As its await call, The app will show splash screen and Firebase may not initialise so I proceeded next with another FutureBuilder for home screen to make sure Firebase app is initialised before I use FirebaseAuth.
home: FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString(),
style: TextStyle(fontSize: 10));
}
if (snapshot.connectionState == ConnectionState.done) {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
return snapshot.hasData ? Home() : AuthPage();
},
);
} else {
return Text('');
}
})
You can initialize in the main.dart file as well like this using FutureBuilder.
future: Firebase.initializeApp(),
Look at this example.
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'NEWSAPI.org',
home: SplashScreen(),
routes: <String, WidgetBuilder>{
SPLASH_SCREEN: (BuildContext context) => SplashScreen(),
},);
},
);
}
}
you neeed to add await FirebaseApp.initializeApp() in main function remember to add await in main function
On my case, I added web support to my existing project.
The one thing which solved the issue is,
In the web/index.html file
Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0
Snippet
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
<script>
var firebaseConfig = {
....
}
If you are working on a project in which the firebase_core was preconfigured and then you are trying to add new packages it will give that error.
You have to first remove firebase_core: from pubsec.yaml and then save the file and reconfigure it through flutter pub add firebase_core and then flutterfire configure.
Then you can add any new packages.
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
Make sure you are using the right/official version of the firebase package.
I was using:
firebase_core_dart: <version-number>
at: https://pub.dev/packages/firebase_core_dart
instead of the official
firebase_core: <version-number>
at https://pub.dev/packages/firebase_core
Using the first option, I got the initialized when using:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
).whenComplete(
() => print('FIREBASE INITIALIZED================>'));
but the authentication failed with the error message described by the OP.
Try the below code. It will resolve the issue for both IOS and Android.
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isIOS) {
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "found in your google service-info.plist",
appId: "found in your google service-info.plist",
messagingSenderId: "found in firebase",
projectId: "found in firebase"),
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}
For Flutter Users
If you've set Firebase correctly, do not forget to add
await
before
Firebase.initializeApp();
That is mainly the problem with that Exception.
And since it's a Future, do this:
Future<void> main() async {
await Firebase.initializeApp();
In my case it was because for the Web version you have to manually add stuff in the index.html file, not only the .js dependency, but the configuration. See Web Installation.
We tend to forget that for most stuff Flutter is compiled to the target without the need to change anything target-specific, but in this case one must add the configuration for each target.
Use This for flutter :
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.getAnalytics(app);
Instead of this
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
I wanted to comment. But this issue have lot of trails.
For my case.
I was initializing Injection Container Before Firebase.
Hierarchy needs to be check.
Hive.init(directory.path);
await Firebase.initializeApp();// before
await di.init();
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
like this
The problem for me was I initialized it without "await":
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
The correct way is:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem?
This is an excerpt of my code
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Center(
child: Container(
child: RaisedButton(
onPressed: () {
FirebaseAuth.instance.signOut().then((value) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
LoginScreen()));
});
},
child: Text("Logout"),
)
)
)
);
}
}
Below is the thrown exception
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24 _invoke1 (dart:ui/hooks.dart:267:10)
#25 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer:
TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Starting Since August 17 2020
All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:
First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
firebase_core : ^0.5.0
# cloud_firestore: ^0.14.0 other firebase dependencies
Then you have to call Firebase.initializeApp():
First Example
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return SomethingWentWrong();
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return MyAwesomeApp();
}
// Otherwise, show something whilst waiting for initialization to complete
return Loading();
},
);
}
}
Second Example with Firestore:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstRoute(title: 'First Route'),
);
}
}
class FirstRoute extends StatefulWidget {
FirstRoute({Key key, this.title}) : super(key: key);
final String title;
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("test"),
),
body: FutureBuilder(
future: getData(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
children: [
Container(
height: 27,
child: Text(
"Name: ${snapshot.data.data()['name']}",
overflow: TextOverflow.fade,
style: TextStyle(fontSize: 20),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
));
}
Future<DocumentSnapshot> getData() async {
await Firebase.initializeApp();
return await FirebaseFirestore.instance
.collection("users")
.doc("docID")
.get();
}
}
Third Example:
Initialize it in initState() then call setState() which will call the build() method.
#override
void initState() {
super.initState();
Firebase.initializeApp().whenComplete(() {
print("completed");
setState(() {});
});
}
Fourth Example:
Initialize it in the main() method after calling WidgetsFlutterBinding.ensureInitialized();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Note: You only have to call initializeApp() once
Add to pubspec.yaml
firebase_core :
add to main.dart
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
If you followed Peter's answer and are still getting the same error, check to make sure anything else you have in your main function comes after the await Firebase.initializeApp() call, like so:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runApp(MyApp());
}
Since August 2017, all Firebase services have been updated so that you have to call Firebase.initializeApp() in your main before you can use any of the Firebase products, for example:
If you want to use the firebase_core plugin in a flutter application, then in your pubspec.yaml file add the firebase_core as below
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.19.1
Then call the Firebase.initializeApp(): in your app. same as something below:
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Dart-only initialization (Recommended)
Initialize Firebase on all platforms using CLI.
No need to add any native code.
No need to download any Google services file.
Install FlutterFire CLI
dart pub global activate flutterfire_cli
(Optional) Add the following line to your ~/.zshrc file and save it
export PATH="$PATH":"$HOME/.pub-cache/bin"
Run the configure:
flutterfire configure
Press enter to configure all the platforms
You should now have a lib/firebase_options.dart file. Import this file in your main.dart and use Firebase.initializeApp.
import 'firebase_options.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// This is the last thing you need to add.
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(...);
}
Migrating to Dart-only initialization:
If you already have an existing application, you can migrate it in the following ways.
Android:
Delete google-services.json file from <flutter-project>/android/app:
Delete the following line in <flutter-project>/android/build.gradle file
Delete the following line in <flutter-project>/android/app/build.gradle file
iOS
Open <flutter-project>/ios/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
macOS
Open <flutter-project>/macos/Runner.xcworkspace file in Xcode and delete the GoogleService-Info.plist file from the Runner.
More information can be found here
First, add this dependency:
firebase_core :
Second: in the project main function, add these two lines and make the function async:
void main() async {
// These two lines
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
//
runApp(MyApp());
}
Now you can use Firebase normally in any file or widget in the project.
The FutureBuilder widget will work either, but you must add it every time you want to access Firebase.
Peter's answer is perfect!! But if you still get an error in your code and following the Flutter Firebase codelab, note that those tutorials are outdated as of August 2020 and not updated yet.
You need to do many other changes like:
replace .data with .data()
replace updateData with update
Flutter Web with Firebase
If you are using Flutter Web with Firebase make sure you have the SDKs installed in the body tag of your ./web/index.html
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>
Furthermore, make sure you call firebase.initializeApp(...) with the configuration parameters in the index.html as well.
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIz...",
authDomain: "...",
databaseURL: "https://<project-name>.firebaseio.com",
projectId: "...",
storageBucket: "<project-name>.appspot.com",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
At last configure firebase as described in Peter Haddad's answer:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Since Flutter versions 2.8, FlutterFire can now be initialized from Dart on all platforms using the Firebase.initializeApp function. There's a more simple and quicker way to initialize a firebase project, instead of downloading the .json and .plist file from the firebase console and placing them into your Flutter project folders which can result in several warnings. This is a problem I've experienced several times and here's how I solved it.
After creating your project in the firebase console steps here and installed the Firebase CLI here, please proceed with the following steps:
You can skip step 1 and jump to step 4 if you've already configured your firebase project with flutterfire configure.
From your project root terminal, command:
$ flutterfire configure
// This requires the Firebase CLI to work.
Select firebase project by hitting return or enter.
insert the bundle ID. You can get this by right clicking the ios folder > then click'Open in xcode'. The Bundle Identifier will appear in the right white panel and you'll have to type this in the terminal manually when prompted.
** Proceed to step 5 if you already have the firebase_core plugin installed. **
Install the latest version of the firebase_core plugin by running this command from your project root directory:
$ flutter pub add firebase_core // Adds to pubspec.yaml
Add imports to the main file:
import 'package:firebase_core/firebase_core.dart'; //
import 'firebase_options.dart'; // Generated file
Update your main function to initialize firebase with this async function:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform);
runApp(const YourAppName());
}
See the FlutterFire documentation for more information.
You need to add await Firebase.initializeApp(); which is a Future. Do it inside the dart file that is running your Firebase function like below:
import 'package:firebase_core/firebase_core.dart';
...
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp());
}
If you still have the problem when you leave the app to the main screen, you could add this to whatever .dart file using Firebase:
class App extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
Or in the case of a StatefulWidget:
import 'package:flutter/material.dart';
// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// Set default `_initialized` and `_error` state to false
bool _initialized = false;
bool _error = false;
// Define an async function to initialize FlutterFire
void initializeFlutterFire() async {
try {
// Wait for Firebase to initialize and set `_initialized` state to true
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch(e) {
// Set `_error` state to true if Firebase initialization fails
setState(() {
_error = true;
});
}
}
#override
void initState() {
initializeFlutterFire();
super.initState();
}
#override
Widget build(BuildContext context) {
// Show error message if initialization failed
if(_error) {
return SomethingWentWrong();
}
// Show a loader until FlutterFire is initialized
if (!_initialized) {
return Loading();
}
return MyAwesomeApp();
}
}
For more information, check this link.
This is the way to initialize firebase in 2022
First of all, Install FlutterFire with this link ==>
Flutter Fire Installation Link
After installing FlutterFire, you'll need to add these lines of code in your lib/main.dart file
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Then edit your Main Function as done below
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform,);
runApp(MyApp());
}
This can change in the future, so refer to this link for the latest implementation reference below
Initializing FlutterFire#
In most cases this problem is observed after upgrading the project from older Flutter version to null safety. These things should be checked:
Ensure you have firebase-core in pubscpec.yaml
Import firebase core:
import 'package:firebase_core/firebase_core.dart';
Init Firebase before any call - preferably inside main.dart so it is executed before any other implementation:
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
From offical documentation.
I needed to reconfigure the Firebase app with FlutterFire cli.
https://firebase.flutter.dev/docs/cli
Install firebase-tool via NPM: npm install -g firebase-tools
Install flutterfire cli: dart pub global activate flutterfire_cli
Run this command to configure firebase in your project: flutterfire configure
Follow the above link and initialise as follows:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
As its await call, The app will show splash screen and Firebase may not initialise so I proceeded next with another FutureBuilder for home screen to make sure Firebase app is initialised before I use FirebaseAuth.
home: FutureBuilder(
future: Firebase.initializeApp(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString(),
style: TextStyle(fontSize: 10));
}
if (snapshot.connectionState == ConnectionState.done) {
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
return snapshot.hasData ? Home() : AuthPage();
},
);
} else {
return Text('');
}
})
You can initialize in the main.dart file as well like this using FutureBuilder.
future: Firebase.initializeApp(),
Look at this example.
void main() {
runApp(App());
}
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder(
// Initialize FlutterFire
future: Firebase.initializeApp(),
builder: (context, snapshot) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'NEWSAPI.org',
home: SplashScreen(),
routes: <String, WidgetBuilder>{
SPLASH_SCREEN: (BuildContext context) => SplashScreen(),
},);
},
);
}
}
you neeed to add await FirebaseApp.initializeApp() in main function remember to add await in main function
On my case, I added web support to my existing project.
The one thing which solved the issue is,
In the web/index.html file
Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0
Snippet
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
<script>
var firebaseConfig = {
....
}
If you are working on a project in which the firebase_core was preconfigured and then you are trying to add new packages it will give that error.
You have to first remove firebase_core: from pubsec.yaml and then save the file and reconfigure it through flutter pub add firebase_core and then flutterfire configure.
Then you can add any new packages.
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
Make sure you are using the right/official version of the firebase package.
I was using:
firebase_core_dart: <version-number>
at: https://pub.dev/packages/firebase_core_dart
instead of the official
firebase_core: <version-number>
at https://pub.dev/packages/firebase_core
Using the first option, I got the initialized when using:
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
).whenComplete(
() => print('FIREBASE INITIALIZED================>'));
but the authentication failed with the error message described by the OP.
Try the below code. It will resolve the issue for both IOS and Android.
import 'dart:io';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isIOS) {
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "found in your google service-info.plist",
appId: "found in your google service-info.plist",
messagingSenderId: "found in firebase",
projectId: "found in firebase"),
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}
For Flutter Users
If you've set Firebase correctly, do not forget to add
await
before
Firebase.initializeApp();
That is mainly the problem with that Exception.
And since it's a Future, do this:
Future<void> main() async {
await Firebase.initializeApp();
In my case it was because for the Web version you have to manually add stuff in the index.html file, not only the .js dependency, but the configuration. See Web Installation.
We tend to forget that for most stuff Flutter is compiled to the target without the need to change anything target-specific, but in this case one must add the configuration for each target.
Use This for flutter :
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.getAnalytics(app);
Instead of this
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
I wanted to comment. But this issue have lot of trails.
For my case.
I was initializing Injection Container Before Firebase.
Hierarchy needs to be check.
Hive.init(directory.path);
await Firebase.initializeApp();// before
await di.init();
Initialise with firebase options
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform).catchError((e){
print(" Error : ${e.toString()}");
});
}
like this
The problem for me was I initialized it without "await":
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
The correct way is:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();