简体   繁体   中英

Firebase Exception building a Consumer<UserManager> // [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

I'm caught up in the middle of this error, and I can't even begin to think of a way to fix it. I tryed in many ways to put up the Firebase.initializeApp(); into my code, but I didn't manage to do it the right way. I already have the packages in my pubspec.yaml, including Firebase Core, Auth, Cloud Firestore... I believe that my user manager is correct, but do I have to call the firebase initialize in it? I put the initialize Firebase on my main, just like this:

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

This was the exception:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FirebaseException was thrown building Consumer<UserManager>(dirty, dependencies: [_InheritedProviderScope<UserManager>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

The relevant error-causing widget was: 
  Consumer<UserManager> file:///C:/Users/adrie/Documents/renata_osorio_nails/lib/screens/login/login_screen.dart:40:22
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      new UserManager (package:renata_osorio_nails/models/user_manager.dart:11:42)
#4      MyApp.build.<anonymous closure> (package:renata_osorio_nails/main.dart:20:22)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

And my code in login screen is as it follows:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:renata_osorio_nails/helpers/validators.dart';
import 'package:provider/provider.dart';
import 'package:renata_osorio_nails/models/user_manager.dart';
import 'package:renata_osorio_nails/models/user.dart';

class LoginScreen extends StatelessWidget {

  final TextEditingController emailController = TextEditingController();
  final TextEditingController passController = TextEditingController();
//Controladores de texto

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  //Chave de formulário
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
//Chave Snackbar

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: const Text('Entrar'),
        centerTitle: true,
        actions: [FlatButton(
          onPressed: (){
            Navigator.of(context).pushReplacementNamed('/signup');
          },
          textColor: Colors.white,
          child: const Text('CRIAR CONTA',
          style: TextStyle(fontSize: 14),),
        )],
      ),
      body: Center(
        child: Card(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            child: Form(
              key: formKey,
              child: Consumer<UserManager>(
                builder: (_, userManager, child){
                  return ListView(
                    padding: const EdgeInsets.all(16),
                    shrinkWrap: true,
                    children: [
                      TextFormField(
                        controller: emailController,
                        enabled: !userManager.loading,
                        decoration: const InputDecoration(hintText: 'E-mail'),
                        keyboardType: TextInputType.emailAddress,
                        autocorrect: false,
                        validator: (email) {
                          if(!emailValid(email))
                            return 'E-mail inválido';
                          return null;
                        },
                      ),
                      const SizedBox(
                        height: 16,
                      ),
                      TextFormField(
                        controller: passController,
                        enabled: !userManager.loading,
                        decoration: const InputDecoration(hintText: 'Senha'),
                        autocorrect: false,
                        obscureText: true,
                        validator: (pass) {
                          if (pass.isEmpty || pass.length < 8)
                            return 'Senha inválida';
                          return null;
                        },
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: FlatButton(
                          onPressed: () {},
                          padding: EdgeInsets.zero,
                          child: const Text('Esqueci minha senha'),
                        ),
                      ),
                      const SizedBox(
                        height: 16,
                      ),
                      SizedBox(
                        height: 44,
                        child: RaisedButton(
                          onPressed: userManager.loading ? null : () {
                            if(formKey.currentState.validate()){
                              context.read()<UserManager>().signIn(
                                  user: AppUser(
                                    email: emailController.text,
                                    password: passController.text,
                                  ),
                                  onFail: (e){
                                    scaffoldKey.currentState.showSnackBar(
                                        SnackBar(
                                          content: Text ('Falha ao entrar: $e'),
                                          backgroundColor: Colors.red,
                                        )
                                    );
                                  },
                                  onSuccess: (){
                                    //TODO: Fechar a tela de login
                                  }
                              );}},
                          color: Theme.of(context).primaryColor,
                          disabledColor: Theme.of(context).primaryColor.
                              withAlpha(100),
                          textColor: Colors.white,
                          child: userManager.loading ?
                          CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation(Colors.white),
                          ) :
                          const Text(
                            'Entrar',
                            style: TextStyle(fontSize: 18),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            )),
      ),
    );
  }
}

How can I fix this?

Have you checked if the line is executed? If it isn't, try putting the line before the runApp() call or in the initState() method of your widget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM