简体   繁体   中英

Unable to sign up using Firebase Auth in Flutter

I am using Firebase for my app, I have set up everything properly and Firebase Firestore is working without any problem and I am able to Read and Write data there but when I tried to create a user in Firebase I am getting this message in debug console:

I/BiChannelGoogleApi( 2228): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq@fc008c3
W/DynamiteModule( 2228): Local module descriptor class for com.google.firebase.auth not found.
I/FirebaseAuth( 2228): [FirebaseAuth:] Preparing to create service connection to gms implementation
I/lutter_firebase( 2228): type=1400 audit(0.0:1201): avc: denied { sendto } for path="/dev/socket/logdw" scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:init:s0 tclass=unix_dgram_socket permissive=1
E/GmsClientSupervisor( 2228): Timeout waiting for ServiceConnection callback com.google.firebase.auth.api.gms.service.START
E/GmsClientSupervisor( 2228): java.lang.Exception
E/GmsClientSupervisor( 2228):   at com.google.android.gms.common.internal.zze.handleMessage(Unknown Source:53)
E/GmsClientSupervisor( 2228):   at android.os.Handler.dispatchMessage(Handler.java:101)
E/GmsClientSupervisor( 2228):   at com.google.android.gms.internal.common.zze.dispatchMessage(Unknown Source:8)
E/GmsClientSupervisor( 2228):   at android.os.Looper.loop(Looper.java:164)
E/GmsClientSupervisor( 2228):   at android.app.ActivityThread.main(ActivityThread.java:6541)
E/GmsClientSupervisor( 2228):   at java.lang.reflect.Method.invoke(Native Method)
E/GmsClientSupervisor( 2228):   at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/GmsClientSupervisor( 2228):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
W/DynamiteModule( 2228): Local module descriptor class for com.google.firebase.auth not found.
I/FirebaseAuth( 2228): [FirebaseAuth:] Preparing to create service connection to gms implementation

Here is the pubspec.yaml file:

name: chat_app_flutter_firebase
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.3.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  cloud_firestore: ^0.13.5
  firebase_auth: ^0.16.0


dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:

  uses-material-design: true

auth_screen.dart

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

import '../widgets/auth/auth_form.dart';

class AuthScreen extends StatefulWidget {
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;

  void _submitAuthForm(
    String email,
    String password,
    String username,
    bool isLogin,
    BuildContext ctx,
  ) async {
    AuthResult authResult;

    try {
      setState(() {
        _isLoading = true;
      });
      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
        await Firestore.instance
            .collection('users')
            .document(authResult.user.uid)
            .setData({
          'username': username,
          'email': email,
        });
      }
    } on PlatformException catch (err) {
      var message = 'An error occurred, pelase check your credentials!';

      if (err.message != null) {
        message = err.message;
      }

      Scaffold.of(ctx).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Theme.of(ctx).errorColor,
        ),
      );
      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      print(err);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(
        _submitAuthForm,
        _isLoading,
      ),
    );
  }
}

auth_form.dart

import 'package:flutter/material.dart';

class AuthForm extends StatefulWidget {
  AuthForm(
    this.submitFn,
    this.isLoading,
  );

  final bool isLoading;
  final void Function(
    String email,
    String password,
    String userName,
    bool isLogin,
    BuildContext ctx,
  ) submitFn;

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

class _AuthFormState extends State<AuthForm> {
  final _formKey = GlobalKey<FormState>();
  var _isLogin = true;
  var _userEmail = '';
  var _userName = '';
  var _userPassword = '';

  void _trySubmit() {
    final isValid = _formKey.currentState.validate();
    FocusScope.of(context).unfocus();

    if (isValid) {
      _formKey.currentState.save();
      widget.submitFn(_userEmail.trim(), _userPassword.trim(), _userName.trim(),
          _isLogin, context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        margin: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  TextFormField(
                    key: ValueKey('email'),
                    validator: (value) {
                      if (value.isEmpty || !value.contains('@')) {
                        return 'Please enter a valid email address.';
                      }
                      return null;
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email address',
                    ),
                    onSaved: (value) {
                      _userEmail = value;
                    },
                  ),
                  if (!_isLogin)
                    TextFormField(
                      key: ValueKey('username'),
                      validator: (value) {
                        if (value.isEmpty || value.length < 4) {
                          return 'Please enter at least 4 characters';
                        }
                        return null;
                      },
                      decoration: InputDecoration(labelText: 'Username'),
                      onSaved: (value) {
                        _userName = value;
                      },
                    ),
                  TextFormField(
                    key: ValueKey('password'),
                    validator: (value) {
                      if (value.isEmpty || value.length < 7) {
                        return 'Password must be at least 7 characters long.';
                      }
                      return null;
                    },
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    onSaved: (value) {
                      _userPassword = value;
                    },
                  ),
                  SizedBox(height: 12),
                  if (widget.isLoading) CircularProgressIndicator(),
                  if (!widget.isLoading)
                    RaisedButton(
                      child: Text(_isLogin ? 'Login' : 'Signup'),
                      onPressed: _trySubmit,
                    ),
                  if (!widget.isLoading)
                    FlatButton(
                      textColor: Theme.of(context).primaryColor,
                      child: Text(_isLogin
                          ? 'Create new account'
                          : 'I already have an account'),
                      onPressed: () {
                        setState(() {
                          _isLogin = !_isLogin;
                        });
                      },
                    )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

I have previously worked on a similar app with older Flutter SDK and everything worked just fine.

Current Flutter SDK Info:

Flutter 1.17.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision e6b34c2b5c (9 days ago) • 2020-05-02 11:39:18 -0700, Engine • revision 540786dd51 Tools • Dart 2.8.1

GitHub repo : GitHub Repo

Any Help will be highly appreciated

The problem was with my Emulator, ran it on the physical device and it worked.

I was using Genymotion emulator and it did not have Play Store installed in it, so I installed them using GApps and this solved the issue from emulator too.

Also, using emulator from Android Studio having Play Store services does the trick.

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