我正在尝试验证与Google帐户和电子邮件的连接是否成功。 我不确定依赖关系版本是否存在问题,即使我已经在网络上检查了几次,还是我的代码不正确
app.gradle
implementation 'com.google.firebase:firebase-auth:19.1.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
渐变
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
main.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:authentication/ui/home.dart';
import 'package:authentication/ui/login.dart';
import 'package:authentication/ui/splash.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MainScreen(),
);
}
}
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context,AsyncSnapshot<FirebaseUser> snapshot) {
if(snapshot.connectionState == ConnectionState.waiting)
return SplashPage();
if(!snapshot.hasData || snapshot.data == null)
return LoginPage();
return LoginPage();
},
);
}
}
firebase实用程序
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthProvider {
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<bool> signInWithEmail(String email, String password) async{
try {
AuthResult result = await _auth.signInWithEmailAndPassword(email: email,password: password);
FirebaseUser user = result.user;
if(user != null)
return true;
else
return false;
} catch (e) {
return false;
}
}
Future<void> logOut() async {
try {
await _auth.signOut();
} catch (e) {
print("error logging out");
}
}
Future<bool> loginWithGoogle() async {
try {
GoogleSignIn googleSignIn = GoogleSignIn();
GoogleSignInAccount account = await googleSignIn.signIn();
if(account == null )
return false;
AuthResult res = await _auth.signInWithCredential(GoogleAuthProvider.getCredential(
idToken: (await account.authentication).idToken,
accessToken: (await account.authentication).accessToken,
));
if(res.user == null)
return false;
return true;
} catch (e) {
print(e.toString());
return false;
}
}
}
飞溅
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
@override
Widget build(BuildContext context){
return Scaffold(
body: Container(
color: Theme.of(context).primaryColor,
child: SafeArea(
child: Container(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(
backgroundColor: Colors.white,
),
const SizedBox(height: 10.0),
Text("Loading", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
fontSize: 18.0
),),
],
),
),
),
),
);
}
}
登录
import 'package:authentication/utils/firebase_auth.dart';
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
TextEditingController _emailController;
TextEditingController _passwordController;
@override
void initState() {
super.initState();
_emailController = TextEditingController(text: "");
_passwordController = TextEditingController(text: "");
}
@override
Widget build(BuildContext context){
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 100.0),
Text("Login", style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0
),),
const SizedBox(height: 20.0),
RaisedButton(
child: Text("Login with Google"),
onPressed: () async {
bool res = await AuthProvider().loginWithGoogle();
if(!res)
print("error logging in with google");
},
),
TextField(
controller: _emailController,
decoration: InputDecoration(
hintText: "Enter email"
),
),
const SizedBox(height: 10.0),
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
hintText: "Enter password"
),
),
const SizedBox(height: 10.0),
RaisedButton(
child: Text("Login"),
onPressed: ()async {
if(_emailController.text.isEmpty || _passwordController.text.isEmpty) {
print("Email and password cannot be empty");
return;
}
bool res = await AuthProvider().signInWithEmail(_emailController.text, _passwordController.text);
if(!res) {
print("Login failed");
}
},
)
],
),
),
),
);
}
}
家
import 'package:authentication/utils/firebase_auth.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Home page"),
RaisedButton(
child: Text("Log out"),
onPressed: (){
AuthProvider().logOut();
},
)
],
),
),
);
}
}
尝试通过电子邮件和Google帐户连接时登录
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device Android SDK built for x86...
D/EGL_emulation(12507): eglMakeCurrent: 0x9d385540: ver 2 0 (tinfo 0x9d383480)
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/zygote (12507): Do partial code cache collection, code=29KB, data=21KB
I/zygote (12507): After code cache collection, code=28KB, data=21KB
I/zygote (12507): Increasing code cache capacity to 128KB
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/flutter (12507): PlatformException(exception, Unknown, null)
I/flutter (12507): error logging in with google
D/EGL_emulation(12507): eglMakeCurrent: 0xa67b2940: ver 2 0 (tinfo 0x86e94740)
I/zygote (12507): Do partial code cache collection, code=61KB, data=42KB
I/zygote (12507): After code cache collection, code=60KB, data=42KB
I/zygote (12507): Increasing code cache capacity to 256KB
I/BiChannelGoogleApi(12507): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzao@d9d6493
D/FirebaseAuth(12507): Notifying id token listeners about user ( LnyMICjEyJNjtqKlCo5Qd8gAqva2 ).