1.はじめに
新たに6つのAndroidStudio&Flutter&Firebase記事を書いている。以下は内容、
- 【Flutter/Dart】Firebaseを使おう
https://qiita.com/my_programming/private/7b3251701183ff59b97c - 【Flutter/Dart】Firebase Authenticationを使って認証アプリを作ろう
- 【Flutter/Dart】Firebase/Firestoreを使ったチャットアプリを作ろう
https://qiita.com/my_programming/private/ad0f7a5f7637a1a37842 - 【Flutter/Dart】Firebase/Firestoreを使ったToDoアプリを作ろう
https://qiita.com/my_programming/private/2da77f3a36bf120761c5 - 【Flutter/Dart】Firebase/HostingでWebアプリを外部公開しよう
https://qiita.com/my_programming/private/5950b7e27161dc9ec838 - 【Flutter/Dart】Firebase/Firestoreを使ったBlogアプリを作ろう
https://qiita.com/my_programming/private/6f8515dca825e55d0f07
Firebase AuthenticationはSDKを使用してモバイルアプリとの統合を非常に簡単にする事前構成済みのバックエンドサービスである。認証プロセスのためにバックエンドインフラを自作する必要はない。Firebaseは、Google、Facebook、GitHubなどの一般的なIDプロバイダーとの統合もサポートしている。Firebase AuthenticationをFlutterで実装する方法を説明する。
2.認証アプリを作ろう
FirebaseプロジェクトからAuthenticationを選択する。
![step2_1_1.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fedbab3f9-024c-5206-9808-5dc04ccac273.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=bf7bc43a233522205958e8d725eb34a7)
始める
を押す。
![step2_1_2.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F11f35167-5475-07f8-473a-a55bd91c0a59.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=c250baace2630689f634ad5d5de6bb96)
今回は例としてメールアドレスで認証することとしメール/パスワード
を選択する。
![step2_1_3.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F2d6eaad4-868b-b739-f5cd-13c7ffef628b.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=5a5a64deb706a14a311eb0f43897b709)
メール/パスワード
を有効
にする。
![step2_1_4.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F7bdf839e-aa0c-29e4-ecd4-576f131cce3e.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=ddcac4bb7b3ed80a6fe71fd49834c77f)
以下の画面が表示されることを確認する。
![step2_1_5.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F07f2d390-1a3d-c09a-4617-714e380bb444.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=e3b61bc56291a1e3327a3296fdce51c1)
プロジェクトのトップ画面でアンドロイドマーク
を押す。
![step2_1_5_2.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Ff3df71a5-7801-55eb-60f3-abd59b0369a4.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=675864678792d292d057beb905bcf7e1)
Flutterのプロジェクトを作成する。プロジェクト名を例としてmy_auth_app
とする。
![step2_1_6.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fd2d53374-02d7-13b5-6dbf-54bc6b18817a.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=422c50d1ac39461fc1724261d22e9f22)
android/app/build.gradle
のapplicationId
をコピーする。
![step2_1_7.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fb03f0568-dc32-79f7-fd57-14944a2611ad.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=2598be053bc48e6abe51bff39562efcb)
アプリを登録するためにapplicationId
をパッケージ名にペーストする。他は空欄のままでよくアプリを登録
を押す。
![step2_1_8.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fbbd0c616-1adb-9d9b-7fae-532f9b456b10.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=62103827a7e4825c0b7904bac2f17929)
構成ファイルgoogle-services.json
をダウンロードする。
![step2_1_9.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F863dd837-b78f-5b6f-5257-d354fde9fbf7.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=6515b3ad4ec33267cefd13f51a560d9e)
ダウンロードしたファイルをandroid/app/build.gradle
と同じフォルダに置く。
![step2_1_10.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F03796f56-55c6-25a9-bcc0-2ca5179de152.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=052ddf263f70cf5192f4ab8015246f90)
Firebase SDKを追加するために中段にあるclasspath
をコピーする。
![step2_1_11.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F7c4d8946-dc92-724d-3f29-477ffb1ac8a4.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=a02d194f03a2cf358707078ced8378c8)
classpath
をandroid/build.gradle
の中にコピーする。
![step2_1_12.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fda868332-aba5-603f-0d17-cd808c8b0759.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=ee490736ebb6c4319ce6e6a6f2769dfd)
2つ目のidをコピーする。
android/app/build.gradle
にidをペーストしてapply plugin: 'com.google.gms.google-services'
の通りに書き換える。
![step2_1_13.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F4bff7ec5-becd-27b6-5414-c4b91bca8be3.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=568d09052e81c461101a2352a45e6098)
同様にdependencies
の中のimplementation
の2行をコピーしてandroid/app/build.gradle
にペーストする。
![step2_1_14.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F50e16093-9b1c-ee37-a95f-bce474812aba.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=f72c0cdf273d5bdf4fa6c90eb0e472dc)
FirebaseのSDKを追加
にて次へ
を押してアプリへのFirebaseの追加を完了する。
![step2_1_15.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fcfa19c08-b631-c1b3-8d7e-936e11c381da.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=cde1a87820bca1e5172ffce5b820a39e)
2つのパッケージをdart package
で検索、コピーしたバージョン情報をpubspec.yaml
にペースト、右上のPub get
を押す。
![step2_1_16.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Ffee73ef1-065e-71ce-aa62-f95d1e013983.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=229e9a65395299bc4c921adbc6ed9f34)
AuthenticationのUsersタブを開いて下部の様な画面になっていることを確認する。この後、アプリから登録した認証情報が画面に表示される様に様になる。
![step2_1_17.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F0ee55710-aee3-e006-d892-b3356841dd7a.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=27e10de9c9da506478ae1c2fc9138afd)
android/app/build.gradle
のminSdkVersionを23に、targetSdkVersionを30に変更する。アプリを作成する時期に応じてこれらの数字は増えていく。最適な数字についてはアプリをビルドするときにヒントとして推奨値をAndroid Studioが教えてくれる。
![step2_1_18.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F00439dba-e870-74e7-6f7c-8c90ee61821d.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=36ba0ed058c642bec48b1cfd66107219)
lib/main.dartに認証用のコードを記述。
まず、import文でパッケージを読み込む。
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
FlutterでFirebaseのパッケージを使用する前にFirebase.initializeApp()を呼び出す必要がある。以下のコマンドはFirebaseのバージョンが古いと記述が異なる。
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
MyAppというStatelessWidgetを呼び出す。
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(new MyApp());
}
StatelessWidgetからAuthAppPageという名前のStatefulWidgetを呼び出す。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase_Auth_App',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const AuthAppPage(title: 'Firebase_Auth_App'),
);
}
}
以下にコアとなるユーザー登録とログイン確認のコードを記述する。
class AuthAppPage extends StatefulWidget {
const AuthAppPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<AuthAppPage> createState() => _AuthAppPageState();
}
class _AuthAppPageState extends State<AuthAppPage> {
// Registration Field Email Address
String registerUserEmail = "";
// Registration Field Password
String registerUserPassword = "";
// Login field email address
String loginUserEmail = "";
// Login field password (login)
String loginUserPassword = "";
// View information about registration and login
String DebugText = "";
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
TextFormField(
// Set labels for text input
decoration: InputDecoration(labelText: "Mail Address"),
onChanged: (String value) {
setState(() {
registerUserEmail = value;
});
},
),
TextFormField(
decoration: InputDecoration(labelText: "6 character long Password"),
// Mask not to show password
obscureText: true,
onChanged: (String value) {
setState(() {
registerUserPassword = value;
});
},
),
const SizedBox(height: 1),
ElevatedButton(
onPressed: () async {
try {
// User Registration
final FirebaseAuth auth = FirebaseAuth.instance;
final UserCredential result =
await auth.createUserWithEmailAndPassword(
email: registerUserEmail,
password: registerUserPassword,
);
// Registered User Information
final User user = result.user!;
setState(() {
DebugText = "Register OK:${user.email}";
});
} catch (e) {
// Failed User Information
setState(() {
DebugText = "Register Fail:${e.toString()}";
});
}
},
child: Text("User Registration"),
),
const SizedBox(height: 1),
TextFormField(
decoration: InputDecoration(labelText: "Mail Address"),
onChanged: (String value) {
setState(() {
loginUserEmail = value;
});
},
),
TextFormField(
decoration: InputDecoration(labelText: "Password"),
obscureText: true,
onChanged: (String value) {
setState(() {
loginUserPassword = value;
});
},
),
const SizedBox(height: 1),
ElevatedButton(
onPressed: () async {
try {
// Try login
final FirebaseAuth auth = FirebaseAuth.instance;
final UserCredential result =
await auth.signInWithEmailAndPassword(
email: loginUserEmail,
password: loginUserPassword,
);
// Succeeded to login
final User user = result.user!;
setState(() {
DebugText = "Succeeded to Login:${user.email}";
});
} catch (e) {
// Failed to login
setState(() {
DebugText = "Failed to Login:${e.toString()}";
});
}
},
child: Text("Login"),
),
const SizedBox(height: 8),
Text(DebugText),
],
),
),
),
);
}
}
アプリを実行すると以下の画面が表示される。上2つのテキスト欄がユーザー登録用、下2つのテキスト欄がログイン確認用である。以下にユーザー登録とログインで幾つかのステータスをデバッグ用ステータスバーで確認できるので以下に紹介する。
![step2_1_30.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F6b6033e0-620a-c0d1-db53-f4f2c969e5b5.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=c2ba5e0cda47ee942cc69c4e3a769c75)
まずユーザー登録用のテキスト欄にメールアドレスを記入。次にパスワードを記入。パスワードが6文字以下だとデバッグ用ステータスバーに6文字以上の記入を求めるエラー文が表示される。
![step2_1_31.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2Fcc989c27-9258-905a-ecad-35df93d8278f.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=7abb603c163208e7d777ad9b9d59f5ef)
メールアドレスが既に存在している場合はデバッグ用ステータスバーに既に同じユーザーメールアドレスが存在するエラー文が表示される。
![step2_1_22.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F85febb25-7bc4-0436-9e75-1010029c5df4.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=6fd2bd57bbb7a2835d899d7e357adbfd)
まだ未登録のユーザーメールアドレス、6文字以上のパスワードを記入してUser Registrationボタン
を押す。
![step2_1_22.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F810edfc5-dc32-7595-cb5b-90bcdc8fe7d4.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=4b8f73bdef10f8e291c5bdbb00106897)
Firebaseにユーザータブを開くと、登録したユーザー情報が追加されていることを確認できる
正しくないパスワードでログインしようとするデバッグ用ステータスバーにユーザー情報が間違っているというエラー文が表示される。
![step2_1_22.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F0cfd5434-0e1e-4001-ca54-8e4fe9aba1c8.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=aed859af895b1c55d815cf7a9f833515)
正しいユーザー情報でログインするとデバッグ用ステータスバーにSucceededの文字が表示される。
![step2_1_22.png](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F892339%2F40dad88f-271a-b736-86a7-0bad4bb2d11e.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=1711cbe56a8e2a381e3074ce6566bb79)
3.まとめ
Firebase AuthenticationをFlutterで実装する方法を学んだ。