Как заставить гугл входить? - PullRequest
0 голосов
/ 21 марта 2020

Привет всем, может кто-нибудь, пожалуйста, помогите мне, как интегрировать вход Google в флаттер, пожалуйста. У меня есть 3 файла регистрации, пользователя и авторизации.

Интеграция не может быть выполнена, как следующие уроки, также я получаю ошибки.

В аутентификации я определяю все функции для подписи, регистрации и выхода.

Может кто-нибудь, пожалуйста, помогите мне, спасибо.

Register.dart

import 'package:flutter/material.dart';
import 'package:logsed/services/auth.dart';
import 'package:logsed/shared/loading.dart';

class Register extends StatefulWidget {

  // For swapping forms
  final Function toggleView;
  Register({this.toggleView});

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

class _RegisterState extends State<Register> {

  final AuthService _auth = AuthService();
  final _formkey = GlobalKey<FormState>();

  // Spinner
  bool loading = false;

  // Text Field State
  String email = '';
  String password = '';
  String error = '';

  @override
  Widget build(BuildContext context) {
    return loading ? Loading() : Scaffold(
      backgroundColor: Colors.brown[100],
      appBar: AppBar(
        backgroundColor: Colors.brown[400],
        elevation: 0.0,
        title: Text('Sign Up'),
        actions: <Widget>[
          FlatButton.icon(
            icon: Icon(Icons.vpn_key),
            label: Text('Sign In'),
            onPressed: () {
              // access it from constructor above
              widget.toggleView();
            }
          ),
        ],
      ),
      body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
         child: Form(
           key: _formkey, // Associating global key with the form key
           child: Column(
             children: <Widget>[
               // For email
               SizedBox(height: 20.0,), // Creates Space between
               TextFormField(
                 // Validation
                 validator: (val) => val.isEmpty ? 'Enter an email' : null,
                 onChanged: (val) {
                   setState(() => email = val);
                },
              ),
               // For password
               SizedBox(height: 20.0,), // Creates Space between
               TextFormField(
                 obscureText: true,
                 // Validation
                 validator: (val) => val.length < 6 ? 'Enter an password for 6 characters long' : null,
                 onChanged: (val) {
                  setState(() => password = val);
                 },
               ),
              // Sign in button
               SizedBox(height: 20.0,), // Creates Space between
               RaisedButton(
                 color: Colors.pink[400],
                 child: Text(
                   'Sign Up',
                   style: TextStyle(
                    color: Colors.white,
                   ),
              ),
                 onPressed: () async {
                   // Validate the form by evaluating it
                   if (_formkey.currentState.validate()) {
                     dynamic result = await _auth.registerWithEmailAndPassword(email, password);
                    // check if null
                     if (result == null) {
                       setState(() => error = 'Please recheck all your credentials');
                     }
                     // Automatically on success goes on home due to STREAM
                   }
                 },
               ),
               SizedBox(height: 20.0,), // Creates Space between
               // ERROR MESSAGES when result is null
               Text(
                 error,
                 style: TextStyle(
                  color: Colors.red,
                   fontSize: 14.0, 
                 ),
               )
             ],
          ),
         ),
      ),
    );
  }
}

auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:logsed/models/user.dart';

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  // create user object based on Firebase user
  User _userFromFirebaseUser(FirebaseUser user) {
    return user != null ? User(uid: user.uid) : null;
  }

  // Auth change user stream
  Stream<User> get user {
    return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
  }

  // sign in annonymously
  Future signInAnonymous() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    }
    catch(e) {
      print(e.toString());
      return null;
    }
  }

  // sign in with email and password
  Future signInWithEmailAndPassword(String email, String password) async {
    try { //Requesting to firebase
    // ceate user
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      // if successfull return this
      return _userFromFirebaseUser(user);
    }
    catch(e) {
      print(e.toString());
      return null;
    }
  }

  // register with email and password
  Future registerWithEmailAndPassword(String email, String password) async {
    try { //Requesting to firebase
    // ceate user
      AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      // if successfull return this
      return _userFromFirebaseUser(user);
    }
    catch(e) {
      print(e.toString());
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    }
    catch(e) {
      print(e.toString());
      return null;
    }
  }
}

user.dart

class User {
  final String uid;
  User({this.uid});
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...