📜  Flutter – 社交媒体身份验证按钮(1)

📅  最后修改于: 2023-12-03 14:41:16.625000             🧑  作者: Mango

Flutter – 社交媒体身份验证按钮

本篇文章介绍了Flutter中用于社交媒体身份验证的按钮控件。该控件可以在注册或登录界面中使用,用于向用户展示可以使用的第三方账号,例如Facebook、Twitter或Google登录等。

使用方法
  1. 在pubspec.yaml文件中添加下列依赖关系:
dependencies:
  flutter_login_facebook: ^1.1.1
  flutter_twitter_login: ^1.1.1
  google_sign_in: ^4.0.1+3
  1. 导入所需库
import 'package:flutter_login_facebook/flutter_login_facebook.dart';
import 'package:flutter_twitter_login/flutter_twitter_login.dart';
import 'package:google_sign_in/google_sign_in.dart';
  1. 创建社会媒体认证按钮
  • Facebook按钮
FacebookLoginButton(
  onPressed: () {
    _loginWithFacebook();
  }
)
  • Twitter按钮
TwitterLogin(
  consumerKey: '',
  consumerSecret: '',
  onPressed: () {
    _loginWithTwitter();
  }
)
  • Google按钮
GoogleSignInButton(
  onPressed: () {
    _loginWithGoogle();
  },
)
  1. 处理社交媒体认证
  • Facebook认证处理:
final FacebookLogin facebookSignIn = new FacebookLogin();
Future _loginWithFacebook() async {
  final result = await facebookSignIn.logIn(['email']);

  switch (result.status) {
    case FacebookLoginStatus.loggedIn:
      final token = result.accessToken.token;
      final graphResponse = await http.get(
          'https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=$token');
      final profile = json.decode(graphResponse.body);
      print(profile);
      break;
    case FacebookLoginStatus.cancelledByUser:
      break;
    case FacebookLoginStatus.error:
      break;
  }
}
  • Twitter认证处理:
final TwitterLogin twitterLogin = new TwitterLogin(
  consumerKey: '',
  consumerSecret: '',
);

Future _loginWithTwitter() async {
  final TwitterLoginResult result = await twitterLogin.authorize();

  switch (result.status) {
    case TwitterLoginStatus.loggedIn:
      final session = result.session;
      print(session);
      break;
    case TwitterLoginStatus.cancelledByUser:
      break;
    case TwitterLoginStatus.error:
      break;
  }
}
  • Google认证处理:
final GoogleSignIn googleSignIn = GoogleSignIn();

Future _loginWithGoogle() async {
  try {
    GoogleSignInAccount user = await googleSignIn.signIn();
    if (user == null) {
      return;
    }
    final GoogleSignInAuthentication googleAuth = await user.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final FirebaseUser firebaseUser =
        (await _auth.signInWithCredential(credential)).user;

    if (firebaseUser != null) {
      // Logged in successfully.
      print('uid:${firebaseUser.uid}');
    }
  } catch (error) {
    print(error);
  }
}
总结

以上是 Flutter 中使用社会媒体认证的按钮控件的全部内容。快速简单地实现社会媒体认证,可以大大减少用户注册和登录的复杂度,在应用程序体验上没有负面影响。