LoginSignup
3
2

More than 3 years have passed since last update.

[Flutter]Firebase Authenticationから直接ユーザーを削除するのはやめよう

Last updated at Posted at 2021-03-21

はじめに

  
以下のリンク先のアプリにてエンジニア
として参加しました。
  

開発期間一ヶ月。文系未経験が大学課題管理アプリを作った話。
この度、大学の友達三名と大学の課題管理アプリを開発しました。 ダウンロード👇(IOS)...

  

つまずいた時のことについて

  
私の担当箇所にて「uid(Unique Identifier)」を取得し、

「存在すれば○○、しなければ△△」

という処理を実装する必要がありました。

その時私は以下のような流れで確認しました。
  

1 : アカウント作成をアプリ上からAPIを呼ぶ

2 : 作成されたらFirebase Authentication上のアカウントを一度削除する。

3 : アプリ側で存在するか確認してみる。
  

この流れだと普通は「存在しない」と判定されるはずですよね。

しかしアプリ上での判定は、

「存在する」

となりました。

「え?なんで??」と思ったので実験用のサンプルを作り動作を確認してみました。
  

  
  
※デュアルディスプレイで録画した為少し見づらくなっており申し訳ありません。
  
動画のようにサンプル上で確認しても、Firebase Authentication上で削除し、再度uidを取得したら
データが残っていることがおわかりかと思います。
  

個人的予想

  
挙動を見る限りおそらくアプリ上、もといローカル上でアカウント作成のAPIコールをした時、

「ローカル上でuidを作成し、それを
 Authenticationに反映させる。
 uidはキャッシュとしてど
 こかに保存しておく。」

と思われます。

ただしDart Package-Puv.devのリファレンスやgitの中身を確認していないのであまり信用しないでくださいね(;・∀・)

もしお時間のある方でリファレンス、git読むことができる方で処理内容が分かった方がおられましたらコメントの方お待ちしております。

最後に & ソースコード

  
上記の問題は、

「ローカルから削除APIをコールする」

で解決できました。

  
  
ーーーーーーーーーーーーーーーーー

各自でFirebaseとアプリの
接続を行ってください。

Authenticationのメール/パスワードを
有効にしてください

・依存関係

pubspec.yaml
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.0

  firebase_core: ^0.7.0
  firebase_auth: ^0.20.1
  cloud_firestore: ^0.16.0+1

  
・ソースコード
  

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Delete Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Delete Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String uid = "uid";
  String getuid = "getuid";
  String deleteuser = "wait delete";
  User me;

  Column CreateAuthfication() {
    return Column(
      children: [
        RaisedButton(
          child: const Text('Create Authfication'),
          color: Colors.blue,
          textColor: Colors.white,
          onPressed: () {
            FirebaseAuth.instance
                .createUserWithEmailAndPassword(
                    email: "example@gmail.com", password: "12345678")
                .then(
                  (value) => {
                    print(value.user.uid),
                    setState(() {
                      me = value.user;
                      uid = me.uid;
                    }),
                  },
                );
          },
        ),
        Text(uid)
      ],
    );
  }

  Column CheckAuthInstance() {
    return Column(
      children: [
        RaisedButton(
          child: const Text('CheckAuthInstance'),
          color: Colors.green,
          textColor: Colors.white,
          onPressed: () {
            try {
              FirebaseAuth.instance.currentUser.uid;

              setState(() {
                getuid = FirebaseAuth.instance.currentUser.uid;
              });
            } on NoSuchMethodError catch (e) {
              setState(() {
                getuid = "null";
              });
            }
          },
        ),
        Text(getuid)
      ],
    );
  }

  Column DeleteAuthInstance() {
    return Column(
      children: [
        RaisedButton(
          child: const Text('DeleteAuthInstance'),
          color: Colors.red,
          textColor: Colors.white,
          onPressed: () {
            try {
              FirebaseAuth.instance.currentUser;

              FirebaseAuth.instance.currentUser.delete();
              setState(() {
                deleteuser = "deleted";
              });
            } on NoSuchMethodError catch (e) {
              setState(() {
                deleteuser = "no exist user";
              });
            }
          },
        ),
        Text(deleteuser)
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CreateAuthfication(),
            CheckAuthInstance(),
            DeleteAuthInstance(),
          ],
        ),
      ),
    );
  }
}

  
  
皆さんも楽しいFlutter & Firebaseライフを楽しみましょう!
  
  

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2