FlutterとFirebaseで認証を行う

FlutterとFirebaseで認証を行う

2022/05/02
Flutter

準備

Firebaseのセットアップ

Firebase CLIをインストール

(こちら)[https://firebase.google.com/docs/cli?hl=ja#setup_update_cli]を参照

Google アカウントで Firebase にログインする

$ firebase login

FlutterFireCLIのインストール

$ dart pub global activate flutterfire_cli

flutterfire configureの実行

$ flutterfire configure

Firebaseに作成したプロジェクトを選択。

i Found 3 Firebase projects.
? Select a Firebase project to configure your Flutter application with ›
❯ アプリ名 (プロジェクト名)
  <create a new project>

アプリで作成するプラットホームを選択。

? Which platforms should your configuration support (use arrow keys & space to select)? ›
✔ android
✔ ios
macos
web

iOSのバンドルIDを設定。 バンドルIDはFirebaseの「作成したプロジェクト > 全般 > マイアプリ」から確認できます。

? Which ios bundle id do you want to use for this configuration, e.g. 'com.example.app'? › iOSのバンドルIDを入力する

プラグインをインストール

以下をインストールします。

main.dartにFirebaseの初期化処理を追加

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

Firebase Authenticationでログイン方法を追加

FirebaseのAuthenticationで、ログイン方法を追加します。
今回は「メールアドレス / パスワード」で認証できるようにします。

Authentication > Sign-in methods >「メールアドレス / パスワード」を選択。

「メールアドレス / パスワード」を有効にして保存をおします。

Authentication画面が以下のようになります。

プラグインをインストール

以下をインストールします。

ユーザー登録

ユーザーを登録する処理は簡単に書くと以下になります。

// 登録
final user = (await FirebaseAuth.instance.createUserWithEmailAndPassword( email: email, password: password)).user;

認証はこちら。

// 認証
final user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: email,password: password)).user;
if(user != null) {
 // 認証OK
}

パスワードリセットはこちら。

await FirebaseAuth.instance.sendPasswordResetEmail(email: email);

なにかお手伝いできることがあればご連絡ください。

お問い合わせはこちらから

※Googleフォームが表示されます