enhar_korfez_41
enhar_korfez_41

Reputation: 39

How to resolve error loading FirebaseOptions from resource? (PlatformException: java.lang.Exception)

I'm trying to create a simple signin/signup application with Firebase, but I'm encountering the following error.
Already tried flutter clean .

E/flutter ( 4727): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly., Exception, Cause: null, Stacktrace: java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly. E/flutter ( 4727): at io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin.lambda$optionsFromResource$4$io-flutter-plugins-firebase-core-FlutterFirebaseCorePlugin(FlutterFirebaseCorePlugin.java:207) E/flutter ( 4727): at io.flutter.plugins.firebase.core.FlutterFirebaseCorePlugin$$ExternalSyntheticLambda2.run(Unknown Source:4) E/flutter ( 4727): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) E/flutter ( 4727): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) E/flutter ( 4727): at java.lang.Thread.run(Thread.java:923) E/flutter ( 4727): , null) E/flutter ( 4727): #0 FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:242:7) E/flutter ( 4727): <asynchronous suspension> E/flutter ( 4727): #1 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89:25) E/flutter ( 4727): <asynchronous suspension> E/flutter ( 4727): #2 Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:31) E/flutter ( 4727): <asynchronous suspension> E/flutter ( 4727): #3 main (package:firebase_signup/main.dart:7:3) E/flutter ( 4727): <asynchronous suspension> E/flutter ( 4727):

Login Code Snippet:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

//Login section

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key); // key düzeltildi

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  TextEditingController email = TextEditingController();
  TextEditingController password = TextEditingController();

  signin()async{
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: email.text,
      password: password.text,
    );

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Login")),
      body: Padding(
        padding: EdgeInsets.all(5), // Padding'in yanına virgül eklendi
        child: Column(
          children: [
            TextField(
              controller: email,
              decoration: InputDecoration(
                hintText: "Enter email",
              ),
            ),
            TextField(
              controller: password,
              decoration: InputDecoration(
                hintText: "Enter password",
              ),
            ),
            ElevatedButton(
                onPressed: ()=>signin(),
                child: Text("Login")
            )
          ],
        ),
      ),
    );
  }
}

Wrapper Code Snippet:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_signup/homepage.dart';
import 'package:firebase_signup/login.dart';
import 'package:flutter/material.dart';

class Wrapper extends StatefulWidget {
  const Wrapper({Key? key}) : super(key: key);

  @override
  State<Wrapper> createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return HomePage();
          } else {
            return Login();
          }
        },
      ),
    );
  }
}

HomePage Code Snippet:

import 'package:flutter/material.dart'; // Cupertino import yerine Material import edildi
import 'package:firebase_auth/firebase_auth.dart'; // FirebaseAuth import edildi

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key); // key düzeltildi

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final user = FirebaseAuth.instance.currentUser;

  signout() async {
    await FirebaseAuth.instance.signOut();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("asd")), // AppBar yazım hatası düzeltildi
      body: Center(
        child: Text('${user!.email}'), // Kullanıcının e-postası eklendi
      ),
      floatingActionButton: FloatingActi`your text`onButton(
        onPressed: () => signout(), // Fonksiyon çağrısı düzgün şekilde yapıldı
        child:Icon(Icons.login_rounded) ,
      ),
    );
  }
}

Upvotes: 1

Views: 5676

Answers (5)

Criss Gibran
Criss Gibran

Reputation: 104

the way how i solved this issue is that I added this line :

id 'com.google.gms.google-services'

to my app/build.gradle in the plugins sections:

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
    id 'com.google.gms.google-services'
}

Upvotes: 0

Greg Quinn
Greg Quinn

Reputation: 2188

What worked for me was to specify com.google.gms.google-services with a version number in plugins, and beneath that, apply the plugin.

app\build.gradle

plugins {
  id "com.android.application"
  id "kotlin-android"    
  id 'com.google.gms.google-services' version '4.4.2'
  // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
  id "dev.flutter.flutter-gradle-plugin"
}

apply plugin: 'com.google.gms.google-services'

android {
  namespace = "com.my.app"

Upvotes: 0

Yauheni Prakapenka
Yauheni Prakapenka

Reputation: 1734

I had the same issue when I implemented push notification:

PlatformException (PlatformException(java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly., Exception, Cause: null, Stacktrace: java.lang.Exception: Failed to load FirebaseOptions from resource. Check that you have defined values.xml correctly.

To fix this issue:

  1. Check that google-services.json is located in the android/app/ directory.

  2. Configure build.gradle for app level in the android/app directory:

  • Add apply plugin: 'com.google.gms.google-services' before android section
apply plugin: 'com.google.gms.google-services' // add

android { 
    namespace "com.example.myapp"
    ...
}
  • Change minSdkVersion to 21

  • Check that namespace and applicationId are the same with package_name in google-services.json

  1. Configure build.gradle for project level in the android directory:

Add to buildscript section dependency 'com.google.gms:google-services:4.3.15'

buildscript {
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.google.gms:google-services:4.3.15' // add
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}
...
  1. Configure pubspec.yaml
dependencies:
  firebase_core: 3.2.0
  firebase_messaging: 15.0.3
  1. Initialize Firebase
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MainApp());
}

Upvotes: 2

pb4now
pb4now

Reputation: 1295

Downgrade your gradle to 4.3.8 from 4.4.0 (and for the future cases downgrade will fix issue as well but another version ofc)

id "com.google.gms.google-services" version "4.3.8" apply false

Upvotes: 7

sanjay c
sanjay c

Reputation: 829

you should update your code should call Firebase.initializeApp before any firebase related call also add option parameter also with it. Better configure through firebase cli will auto generate files

 await Firebase.initializeApp(
      options: FirebaseOptions(
    apiKey: 'key',
    appId: 'id',
    messagingSenderId: 'sendid',
    projectId: 'myapp',
    storageBucket: 'myapp-b9yt18.appspot.com',
  )
    );

created new app, and configured it with cli mode it will generate the options file for all platforms. Just add google-services.json won't be enough from flutte 3.19 it seems

firebase cli config

once the files are generated your firebaseinit code should look like this

 await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform
);

Upvotes: 0

Related Questions