'Begginer in Flutter trying to use FireBase auth

So im really just experimenting to get used to flutter with firebase, so first thing im trying to do in my app its an anonymous authenticantion. With the following code im getting the error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()"

Here is my main

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}

Here is The Sign In screen, where i first tried to use firebase.

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

  @override
  _SignInState createState() => _SignInState();
  }


class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[100],
      appBar: AppBar(
        title: Text('Sign In'),
        backgroundColor: Colors.green[500],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:20.0 , horizontal:50.0,),
        child: ElevatedButton(
          child: Text('Sign In'),
          onPressed: () async{
            dynamic result = await _auth.signInAnon();
            if(result == null) {
              print ('failed');}
              else{
                print('Success');
                print(result);
            }
          },
        ),
      ),
    );
  }
}

And the auth class where i use signInAnon().

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //login anon
  Future signInAnon() async{
    try{
     UserCredential result =  _auth.signInAnonymously() as UserCredential;
     User user = result.user as User;
     return user;
    } catch(e){
        print(e.toString());
        return null;
    }
  }
}

I am following an youtube course form about 2 years ago, so i know firebase changed, but a few recent questions here with the same error have been solved changing the code in main like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
   runApp(const MyApp());
}

After this change the app is showing a white screen and console says it has an error:

Syncing files to device Android SDK built for x86...

E/flutter (15860): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.

E/flutter (15860):

E/flutter (15860): Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp.

E/flutter (15860):

E/flutter (15860): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

E/flutter (15860):

E/flutter (15860): #0 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)

E/flutter (15860):

E/flutter (15860): #1 Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)

E/flutter (15860):

E/flutter (15860): #2 main (package:order_beer/main.dart:10:3)

E/flutter (15860):

E/flutter (15860):

If anybody could help me!



Solution 1:[1]

Wrap await Firebase.initializeApp(); in a try-catch block like so:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
   try{
    await Firebase.initializeApp();
   }catch(e){print(e);}
   runApp(const MyApp());
}

Solution 2:[2]

I'm not sure if this is the case but for your main function try writing it as

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Josteve
Solution 2 KaZami-Ryu