skip to Main Content

I am doing Angela Yu’s flutter course and it is very outdated so I keep coming up against issues like this. I am trying to integrate Firebase into a chat app but for some reason I keep getting now I have implemented Firebase.initializeApp(). I am a bit lost as to why this could be. I have tried cleaning up my pubspec file to no avail. I have attched the errors I am getting at the bottom of the question.

Any help would be greatly appreciated.

Here is my main file

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/screens/welcome_screen.dart';
import 'package:flash_chat/screens/login_screen.dart';
import 'package:flash_chat/screens/registration_screen.dart';
import 'package:flash_chat/screens/chat_screen.dart';

Future<void> main() async {
  //Why we need the below code
  // 1. https://stackoverflow.com/questions/63492211/no-firebase-app-default-has-been-created-call-firebase-initializeapp-in
  // 2. https://stackoverflow.com/questions/63873338/what-does-widgetsflutterbinding-ensureinitialized-do
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(
    FlashChat(),
  );
}

class FlashChat extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // theme: ThemeData.dark().copyWith(
      //     // textTheme: TextTheme(
      //     //   bodyLarge: TextStyle(color: Colors.black54),
      //     // ),
      //     ),
      home: WelcomeScreen(),
      //You cant use the home property if your going to use initial routes as they will conflict with each other
      initialRoute: WelcomeScreen.id,
      //Use this to only write the string once within the welcome screen as a property to avoid errors.
      //Without the word static it brings back a new object, with static is just attached to the class
      routes: {
        //This is a map
        WelcomeScreen.id: (context) => WelcomeScreen(),
        LoginScreen.id: (context) => LoginScreen(),
        RegistrationScreen.id: (context) => RegistrationScreen(),
        ChatScreen.id: (context) => ChatScreen(),
      },
    );
  }
}

Here is my registration and chat screen if that is needed. I added it because it has some Firebase functionalities but I don’t think they even get chance to be used

import 'package:flash_chat/constants.dart';
import 'package:flash_chat/screens/chat_screen.dart';
import 'package:flash_chat/screens/welcome_screen.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/components/rounded_button.dart';
import 'package:firebase_auth/firebase_auth.dart';

class RegistrationScreen extends StatefulWidget {
  static const String id = 'registration_screen';
  @override
  _RegistrationScreenState createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
  //create a new auth instance inside registration screen state, make it private so other classes cant use it.
  final _auth = FirebaseAuth.instance;
  //Create variables to store email and password from the text fields
  late String email;
  late String password;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: EdgeInsets.symmetric(horizontal: 24.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Hero(
              tag: 'logo',
              child: Container(
                height: 200.0,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      Navigator.pushNamed(context, WelcomeScreen.id);
                    });
                  },
                  child: Image.asset(
                    'images/logo.png',
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 48.0,
            ),
            TextField(
              keyboardType: TextInputType.emailAddress,
              textAlign: TextAlign.center,
              onChanged: (value) {
                //Do something with the user input.
                email = value;
              },
              decoration: kTextFieldDecoration.copyWith(
                hintText: 'Enter your email',
              ),
            ),
            SizedBox(
              height: 8.0,
            ),
            TextField(
              obscureText: true,
              textAlign: TextAlign.center,
              onChanged: (value) {
                //Do something with the user input.
                password = value;
              },
              decoration: kTextFieldDecoration.copyWith(
                hintText: 'Enter your password',
              ),
            ),
            SizedBox(
              height: 24.0,
            ),
            RoundedButton(
                colour: Colors.blueAccent,
                pressHandler: () async {
                  //Implement registration capability
                  print(email);
                  print(password);
                  try {
                    final newUser = await _auth.createUserWithEmailAndPassword(
                        email: email, password: password);
                    if (newUser != null) {
                      Navigator.pushNamed(context, ChatScreen.id);
                    }
                  } catch (e) {
                    print(e);
                  }
                },
                title: 'Register')
          ],
        ),
      ),
    );
  }
}

Chat Screen

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';

class ChatScreen extends StatefulWidget {
  static const String id = 'chat_screen';
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final _auth = FirebaseAuth.instance;
  //User replaces FirebaseUser and takes the current logged in users details from firebase and stores them in logged in user.
  late User loggedInUser;

  //trigger the getCurrentUser() function/method
  @override
  void initState() {
    super.initState();
    //call get current user
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        //Check logged in user variable is working correctly;
        print(loggedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                //Implement logout functionality
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      onChanged: (value) {
                        //Do something with the user input.
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      //Implement send functionality.
                    },
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Here is the error messages I am getting in the run section

Launching libmain.dart on sdk gphone64 x86 64 in debug mode...
Running Gradle task 'assembleDebug'...
√  Built buildappoutputsflutter-apkapp-debug.apk.
Installing buildappoutputsflutter-apkapp-debug.apk...
Debug service listening on ws://127.0.0.1:63336/nNuBI5A9VV8=/ws
Syncing files to device sdk gphone64 x86 64...
E/flutter ( 8270): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(null-error, Host platform returned null value for non-null return value., null, null)
E/flutter ( 8270): #0      FirebaseCoreHostApi.optionsFromResource (package:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart:248:7)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #1      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:89:25)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #2      Firebase.initializeApp (package:firebase_core/src/firebase.dart:43:31)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): #3      main (package:flash_chat/main.dart:13:3)
E/flutter ( 8270): <asynchronous suspension>
E/flutter ( 8270): 

2

Answers


  1. You need to provide options of .initializeApp,which will be generated from firebase init cli. You can checkout firebase_options.dart file in lib and then use it.

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
    
    }
    

    More about flutter/setup.

    Login or Signup to reply.
  2. make sure to add google-services.json file in android/app/ folder and in ios/runner

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search