TaillookTech

モバイルアプリ開発を追っています

Flutterでfirebase authを用いてメール認証をする

余談ですが10/27,28に高専プロコンのために徳島へ行ってました. 高専生活最後の高専プロコンが終わりエモい感じです.

この記事ではFlutterアプリでのfirebase_Authを用いたメール認証を行います.

環境

$ flutter --version
Flutter 0.9.4 • channel beta • https://github.com/flutter/flutter.git
Framework • revision f37c235c32 (5 weeks ago) • 2018-09-25 17:45:40 -0400
Engine • revision 74625aed32
Tools • Dart 2.1.0-dev.5.0.flutter-a2eb050044

Firebaseでプロジェクトを追加

f:id:taillook:20181030040211p:plain

ログインプロバイダでメール認証を追加

f:id:taillook:20181030040418p:plain

Flutterプロジェクトを作成

flutter create --org tech.taillook flutter_firebase_auth_sample

pubspec.yamlにfirebase_authを追記

cd flutter_firebase_auth_sample/

vim pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: 0.6.2+1

アプリにFirebaseを追加

iOSの場合

f:id:taillook:20181031001108p:plain

f:id:taillook:20181031001414p:plain

Bundle Identifierを入力し,GoogleService-Info.plistをダウンロード.
これをXcode プロジェクトのルート(ios/Runner)に追加.
ios/Rnner.xcworkspaceをxcodeで開きGoogleService-Info.plistをプロジェクトに追加.

androidの場合

iOSの場合と同じくBundle Identifierを入力してアプリを追加します.
androidの場合はgoogle-services.jsonをダウンロードします.
これをandroid/appに追加.
android/app/build.gradleの最下行にapply plugin: 'com.google.gms.google-services'を追記.
android/build.gradleのbuildscriptのdependenciesにclasspath 'com.google.gms:google-services:4.0.0'を追記.

実装

画面はこれ

f:id:taillook:20181031123209p:plain

コードは以下

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'FirebaseAuth',
      theme: new ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseAuth _firebaseAutn = FirebaseAuth.instance;
  final formkey = new GlobalKey<FormState>();

  String _email;
  String _password;

  Future<String> sginInWithEmailAndPassword(String email, String password) async {
    FirebaseUser user = await _firebaseAutn.signInWithEmailAndPassword(email: email, password: password);
    return user.uid;
  }

  Future<String> createUserWithEmailAndPassword(String email, String password) async {
    FirebaseUser user = await _firebaseAutn.createUserWithEmailAndPassword(email: email, password: password);
    return user.uid;
  }

  bool validateAndSave() {
    final form = formkey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    } else {
      return false;
    }
  }

  void submit() async {
    if (validateAndSave()) {
      try {
        String userId = await sginInWithEmailAndPassword(_email, _password);
        print('Sigind in: $userId');
      } catch (e) {
        print(e);
      }
    }
  }

  void regester() async {
    if (validateAndSave()) {
      try {
          String userId = await createUserWithEmailAndPassword(_email, _password);
          print('Regestered in: $userId');
      } catch (e) {
        print(e);
      }
    }
  }

  @override
    Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text("FirebaseAuth"),
        ),
        body: new Container(
          padding: EdgeInsets.all(20.0),
          child: new Form(
            key: formkey,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: buildInputs() + buildSubmitButtons(),
            ),
          ),
        ),
      );
    }

    List<Widget> buildInputs() {
    return [
      new TextFormField(
        decoration: new InputDecoration(labelText: 'Email'),
        validator: (value) => value.isEmpty ? 'メールアドレスを入力してください' : null,
        onSaved: (value) => _email = value,
      ),
      new TextFormField(
        decoration: new InputDecoration(labelText: 'PassWord'),
        validator: (value) => value.isEmpty ? 'パスワードを入力してください' : null,
        obscureText: true,
        onSaved: (value) => _password = value,
      ),
    ];
  }

  List<Widget> buildSubmitButtons() {
    return [
      new RaisedButton(
        splashColor: Colors.blueGrey,
        child: new Text('Login', style: new TextStyle(fontSize: 20.0)),
        onPressed: submit,
      ),
      new RaisedButton(
        splashColor: Colors.blueGrey,
        child: new Text('Create an Account', style: new TextStyle(fontSize: 20.0)),
        onPressed: regester,
      ),
    ];
  }
}

ログイン・ユーザー作成に成功するとuidがprintされます.