[Day16] Flutter - Firebase Authentication & Google Sign-In ( IOS & Android )

前言

Hi, 我是鱼板伯爵今天要教大家 Firebase Authentication 和开通 Google 登入,教学内容只会撷取片段程序码,建议大家搭配完整程序码来练习。

完整程序码

创建一个 Firebase 专案

取个专案名字下一步到底就可以了,若没有google analytics就点开选单建造一个,然後一样下一步到底。

开启 Google 登入

完成专案创就後点击左边Authentication,然後把google的登入给启用。

储存後你可以看到google的状态变成已启用(绿灯)

创建APP

回到专案总览,以下会介绍IOS和Andriod的创建方式。

Android 设定

第一步

第二步

下载google-services.json放入android/app

第三步

android/day16_android.imldependencies层中加入classpath 'com.google.gms:google-services:4.3.10'

dependencies {
    classpath 'com.android.tools.build:gradle:4.1.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.google.gms:google-services:4.3.10'
}

android/app/build.gradle加入apply plugin: 'com.google.gms.google-services'随便加在最外层就可以了。

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

修改applicationId

第五部

打开终端机输入keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore,密码就打个android然後你会得到SHA1和SHA256。

回到firebase点开控制台溜到最下新增指纹,两个都给他新增上去。


IOS 设定

第一步

输入IOS ID 和 App 名字就可以。

第二步

开启专案把GoogleService-Info.plist放入ios/Runner,然後345步骤都不重要下一步到底。

然後打开XCode右键资料夹加入档案,选择GoogleService-Info.plist

第三步

打开ios/Runner/Info.plistGoogleService-Info.plist里面的REVERSED_CLIENT_ID复制到<string>REVERSED_CLIENT_ID</string>里面。

<!-- Google Sign-In section -->
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <!-- TODO Replace this value: -->
            <!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID -->
            <string>REVERSED_CLIENT_ID</string>
        </array>
    </dict>
</array>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>
<!-- End of the Google Sign-In section -->

安装

如果ios有遇到pod的问题请到ios/Podfile把请版本打开,并更新一下pod repo update

dependencies:
  flutter:
    sdk: flutter
  google_sign_in: ^5.0.5
  firebase_auth: ^3.0.1
  firebase_core: ^1.4.0

实作登入

在main里面做初始化。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

写一个简单的登入和登出的Class,来测试有没有设定成功。

import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';

abstract class AuthRepositoryImpl {
  Future<bool> signInWithGoogle();
  Future<void> signOut();
}

class AuthRepository implements AuthRepositoryImpl {
  final FirebaseAuth _firebaseAuth;
  final GoogleSignIn _googleSignIn;

  AuthRepository()
      : _firebaseAuth = FirebaseAuth.instance,
        _googleSignIn = GoogleSignIn();

  @override
  Future<bool> signInWithGoogle() async {
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    if (googleUser == null) {
      return false;
    }
    final GoogleSignInAuthentication googleAuth =
        await googleUser.authentication;
    final AuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    await _firebaseAuth.signInWithCredential(credential);

    return true;
  }

  @override
  Future<void> signOut() async {
    Future.wait([
      _firebaseAuth.signOut(),
      _googleSignIn.signOut(),
    ]);
  }
}

然後在页面上的按钮使用登入的函式

class LoginPage extends StatelessWidget {
  final AuthRepository _authRepository = AuthRepository();

  LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("LOGIN"),
      ),
      body: Container(
        child: Center(
          child: TextButton(
            onPressed: () async {
              final ok = await _authRepository.signInWithGoogle();
              if (ok) {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder: (context) => HomePage(),
                  ),
                );
              }
            },
            child: Text("SIGN IN"),
          ),
        ),
      ),
    );
  }
}


<<:  DAY04 - 建置程序开发环境

>>:  Day 4【HTML + CSS】於是他开始像灵犬莱西一样到处蒐集证据

视觉化KBARS(1)

昨天完成ticks资料的视觉化之後, 我们下一个目标是k线图的实现, 具体会用到下面的工具, 一样是...

找LeetCode上简单的题目来撑过30天啦(DAY14)

医生说我很健康真是太好了呢,今日题目如下 **题号:2 标题:Add Two Numbers 难度:...

Day 4 : Git 分支与远端仓库

远端仓库 打RPG的时候,队友的占位与分配是很重要的! 後排玩家是要对准BOSS的弱点来个会心一击,...

Day-4 CLA以及bit乘法

CLA以及bit乘法 tags: IT铁人 例题答案 就简单把答案打出来罗~ 小心转换成二位元不要粗...

[Day 20] Edge Impulse + BLE Sense实现唤醒词辨识(上)

在[Day 16]和[Day 17]「TFLM + BLE Sense + MP34DT05 就成了...