skip to Main Content

Notice a few questions here regarding this topic, tried the solutions but still no fix to the problem in my code. I am making a sign up screen for my app in Android Studio, but when I press submit signup form, Flutter gives me this error, although I have initiated Firebase.initializeApp() already in my main.dart file. Why is this showing and how do I fix this?

In my Main.dart file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]); // This makes the phone locked in portrait mode, preventing landscape usage
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  DarkThemeProvider themeChangeProvider = DarkThemeProvider();

  void getCurrentAppTheme() async {
    themeChangeProvider.setDarkTheme = await themeChangeProvider.darkThemePrefs
        .getTheme(); //calling dark theme provider to call dark theme prefs method
  } // fetching theme from shared preferences, if user chose value, last value chosen will be fetched and applied

  @override
  void initState() {
    getCurrentAppTheme();
    super.initState();
    Firebase.initializeApp().whenComplete(() {
      print("Intialised");
      setState(() {});
    });
  }

  final Future<FirebaseApp> _firebaseInitialisation = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {

    return FutureBuilder(
        future: _firebaseInitialisation,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const MaterialApp(

When pressing the button to register in a separate file, the code is

bool _isLoading = false; 
  void _submitFormOnRegister() async {
    final isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();
    setState(() {
      _isLoading = true;
    });
    if (isValid) {
      _formKey.currentState!.save();
      try { //useful to catch any error
        await authInstance.createUserWithEmailAndPassword( //Look below for what authInstance is
            email: _emailTextController.text.toLowerCase().trim(),
            password: _passwordTextController.text.trim());
        print('Registered');
      } on FirebaseException catch (error) {
        UniversalFunctions.errorDialog(subtitle: '${error.message})', context: context);
        setState(() {
          _isLoading = false;
        });
      } catch (error) {
        UniversalFunctions.errorDialog(subtitle: '$error', context: context);
        setState(() {
          _isLoading = false;
        });
      } finally {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

the authInstance is in a separate file:

import 'package:firebase_auth/firebase_auth.dart';

final FirebaseAuth authInstance  = FirebaseAuth.instance;
final User? user = authInstance.currentUser;
final uid = user!.uid;

I suspected the button was activating before the firebase.initialise was being called but I’m not sure as I stated it at the front in the main. I saw a solution to add it to the

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

But it does not work (due to the other code having it locking screen format) and it doesn’t work when I remove that.

2

Answers


  1. You can add this dependency too in pubspecs.yaml file

    firebase_core and try after re running the app.

    Login or Signup to reply.
  2. This is the correct way to initialize Firebase:

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

    You should initialize and await it before the main widget which is MyApp().

    What you are doing is initializing Firebase in the initState which is not an async function that is why you are getting and error.

    If doing this causes an error with your other code, then that error is what you need to resolve.

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