🔏

FlutterFire UI使ってみた!

2022/07/18に公開

コードを少し書くだけで認証機能を作ってくれる😇

今回はこちらのチュートリアル動画を参考にFlutterFire UIに入門してみました

https://www.youtube.com/watch?v=JgqcrQvGFzY

公式ドキュメント

https://firebase.flutter.dev/docs/ui/overview

動画の通りに進めていけば環境構築はできます。

pubspec.yaml

name: fire_ui_app
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.17.3 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.4.2
  flutterfire_ui: ^0.4.2+3
  firebase_core: ^1.19.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

main.dart

import 'package:fire_ui_app/auth_gate.dart';
import 'package:fire_ui_app/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'FlutterFire UI - Auth',
      home: AuthGate(),
    );
  }
}

auth_gate.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterfire_ui/auth.dart';

class AuthGate extends StatelessWidget {
  const AuthGate({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return SignInScreen(providerConfigs: [
              EmailProviderConfiguration(),
            ]);
          }

          return Scaffold(
            appBar: AppBar(
              title: const Text('FlutterFire UI Auth'),
            ),
            body: const SignOutButton(),
          );
        });
  }
}

今のところ、ログアウトボタンのページを表示できている。でも仮のページなので、ファイル新たに作成して、画面遷移先のページ作成します。

home_screen.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterfire_ui/auth.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({
    Key? key,
    required this.user,
  }) : super(key: key);

  final User user;
  
  Widget build(BuildContext context) {
    print(user); // userのデータをデバッグ
    return Scaffold(
      appBar: AppBar(
        title: const Text('FlutterFire UI Auth'),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Column(
          children: [
            Text(
              user.email!,
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold
              ),
            ),
            const SignOutButton()
          ],
        ),
      ),
    );
  }
}

コードを書き変えて、パラメーターを渡せるようにする。
auth_gate.dart

import 'package:fire_ui_app/home_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterfire_ui/auth.dart';

class AuthGate extends StatelessWidget {
  const AuthGate({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return SignInScreen(providerConfigs: [
              EmailProviderConfiguration(),
            ]);
          }

          return HomeScreen(user: snapshot.data!);
        });

  }
}

これで、見た目はダサいが、画面にユーザーのメールアドレスを表示する機能がついている。

Google Sign Inを追加

Dartのパッケージを追加します
https://pub.dev/packages/google_sign_in

pubspec.yaml

name: fire_ui_app
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.17.3 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  firebase_auth: ^3.4.2
  flutterfire_ui: ^0.4.2+3
  firebase_core: ^1.19.2
  google_sign_in: ^5.4.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

Firebaseから、Google-Service-info.pilistをダウンロードして追加する。Firebase CLI使う必要あるのか😅

動画の通りにやってもios buildできない?

info.pilistのコードがバージョンによって違うみたいですね😇
Flutter3.0.3の場合は、
ios/Runner/info.pilist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>$(DEVELOPMENT_LANGUAGE)</string>
	<key>CFBundleDisplayName</key>
	<string>Fire Ui App</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>fire_ui_app</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>$(FLUTTER_BUILD_NAME)</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>$(FLUTTER_BUILD_NUMBER)</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIMainStoryboardFile</key>
	<string>Main</string>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UIViewControllerBasedStatusBarAppearance</key>
	<false/>
	<key>CADisableMinimumFrameDurationOnPhone</key>
	<true/>
	<!-- この下にドキュメントのコードを貼り付ける -->
	<!-- Put me in the [my_project]/ios/Runner/Info.plist file -->
<!-- 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 -->
			<!-- この下にcom.googleusercountent.apps.~を貼り付ける -->
			<string>com.googleusercontent.apps.921169842014-b6j085hcljlcvkf2uoqo648hbe7ukebf</string>
		</array>
	</dict>
</array>
<!-- End of the Google Sign-in Section -->
</dict>
</plist>

コードを編集して、ログイン画面をかっこよくします。

auth_gate.dart

import 'package:fire_ui_app/home_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterfire_ui/auth.dart';

class AuthGate extends StatelessWidget {
  const AuthGate({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
        stream: FirebaseAuth.instance.authStateChanges(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return SignInScreen(
                providerConfigs: const [
                  EmailProviderConfiguration(),
                  GoogleProviderConfiguration(
                      clientId:
                          '921169842014-b6j085hcljlcvkf2uoqo648hbe7ukebf.apps.googleusercontent.com')
                ],
                headerBuilder: (context, constraints, _) {
                  return const CircleAvatar(
                    radius: 75,
                    // images.unsplash.comの画像のパスを貼り付ける
                    backgroundImage: NetworkImage(
                        'https://images.unsplash.com/photo-1658033014478-cc3b36e31a5e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMDR8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=800&q=60'),
                  );
                },
                subtitleBuilder: (context, action) {
                  // 署名画面にいるかを確認するには、アクションパラメーターを使用できる
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(action == AuthAction.signIn
                        ? "FlutterFire UI - Sign In"
                        : "FlutterFire UI - Sign Up"),
                  );
                },
                // footerBuilderを使えば下部にメッセージを表示できる
                footerBuilder: (context, actions) {
                  return const Text(
                    'By signing in, you agree to our terms and conditicons',
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.grey),
                  );
                });
          }

          return HomeScreen(user: snapshot.data!);
        });
  }
}

home_screen.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterfire_ui/auth.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({
    Key? key,
    required this.user,
  }) : super(key: key);

  final User user;
  
  Widget build(BuildContext context) {
    print(user); // userのデータをデバッグ
    return Scaffold(
      appBar: AppBar(
        title: const Text('FlutterFire UI Auth'),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Column(
          children: [
            CircleAvatar(radius: 30, backgroundImage: NetworkImage(user.photoURL!),),
            Text(
              user.displayName!,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold
              ),
            ),
            SizedBox(height: 10),
            Text(
              user.email!,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold
              ),
            ),
            SizedBox(height: 10),
            const SignOutButton()
          ],
        ),
      ),
    );
  }
}

スクリーンショット

Google Sign Inしてみる😇

できた!、昔iOSで、Google Sign In実装できなかったのですが、今回はうまく行きましたね。
info.pilistの設定が良くなかったんでしょうね。

注意点!

NetworkImageを配置して、Google Sign Inしたときに、プロフィール画像を表示できるようになりましたが、email、passwordログインでは、プロフィール画像が存在しないので、ログインすると、画面が赤くなって、nullのエラーが出てしまいますね😱

プロフィール画像を表示しなければエラーは出ないです😅

Androidで、Google Sign Inやってみたのですが、うまくいかなかったですね🤔
google-service.jsonをFirebase側のAndroidの設定をする画面で、SHA1 KEYを貼り付けて、新たにダウンロードして、自動生成されているものを上書きしたのですが、ダメでしたね😇
AndroidってGoogle Sign Inのエラーが多い気がする?
Firebase CLIを使わない方がいいのかもしれない?
私、個人的にGoogle Sign In嫌いなので、使いたくないです〜😇

FlutterWebでも試そうと思ったが、さっき「もういいや〜と」プロジェクトを消してたのを忘れてた😅
Google Sign Inだけは、試していたのだが、エラー出てましたね🤔

Githubのリポジトリに、完成したサンプルを公開しております。参考までにどうぞ😅
https://github.com/sakurakotubaki/FlutterFire-UI

最後に

認証機能ですが、メールアドレスとパスワードのログインの方が使いやすいと個人的には思いますね。
Social Authenticationは、iOSでは使えるのに、Androidでは、使えないという厄介な問題が起きることが、あるので、個人的にはお勧めしませんね😇
私の場合だと、Flutter始めた頃は、iOSに、Social Authenticationを組み込むのが難しかったです。
プロフィール画像が全ての認証機能で使えるように、設計しておかないと、Google Sign Inでしか使えなくて他の認証機能で、ログインすると赤い画面のエラーに悩まされることになる😱

Discussion