Flutter接入Facebook和Google等三方登录

Facebook登录

第三方插件:flutter_facebook_login

DartPub:https://pub.dartlang.org/packages/flutter_facebook_login
Github:https://github.com/roughike/flutter_facebook_login

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Future<Null> signInWithFacebook() async {
var facebookLogin = new FacebookLogin();
var result = await facebookLogin.logInWithReadPermissions(['email']);

switch (result.status) {
case FacebookLoginStatus.loggedIn:
final accessToken = result.accessToken;
Api.getFacebookProfile(accessToken).then((response) {
if (response != null && response.statusCode == 200) {
// 将接口返回的json字符串解析为map类型
Map<String, dynamic> profile = json.decode(response.data);
//print(profile);
User user = GlobalData.user;
user.firstName = profile['first_name'];
user.lastName = profile['last_name'];
user.name = profile['name'];
user.email = profile['email'];
user.avatar = profile['picture']['data']['url'];
user.source = 'facebook';
user.sourceId = profile['id'];
Api.signInSocial(user).then((response) {
if (response != null && response.statusCode == 200) {

}
});
}
});
break;
case FacebookLoginStatus.cancelledByUser:
print('Facebook: cancelledByUser');
break;
case FacebookLoginStatus.error:
print('Facebook: ${result.errorMessage}');
break;
}
}

Google登录

(1)google_sign_in

DartPub:https://pub.dartlang.org/packages/google_sign_in
Github:https://github.com/flutter/plugins/tree/master/packages

(2)firebase_auth

DartPub:https://pub.dartlang.org/packages/firebase_auth
Github:https://github.com/flutter/plugins/tree/master/packages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
void signInWithGoogle() {
googleSignIn().then((FirebaseUser firebaseUser) {
User user = GlobalData.user;
String name = firebaseUser.displayName;
user.name = name;
if (name != null && name.length > 0) {
List<String> names = name.split(' ');
if (names.length == 2) {
user.firstName = names[0];
user.lastName = names[1];
} else if (name.length > 1) {
user.firstName = name.substring(0, 1);
user.lastName = name.substring(1);
} else {
user.firstName = name;
user.lastName = name;
}
}
user.email = firebaseUser.email;
user.avatar = firebaseUser.photoUrl;
Api.signInSocial(user).then((response) {
if (response != null && response.statusCode == 200) {

}
});
}).catchError((e) {
print(e);
});
}

Future<FirebaseUser> googleSignIn() async {
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
FirebaseUser firebaseUser = await _auth.signInWithGoogle(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
User user = GlobalData.user;
user.source = 'google';
user.sourceId = googleUser.id;
print("signed in " + firebaseUser.displayName);
return firebaseUser;
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :