title: Flutter Firebase auth phone and Firestore database
body: <p>I would like when connecting by phone via OTP verification, to know if the account already exists and in this case retrieve its information. But if the account does not exist, create a collection in Firestore database with default information</p>
  <p>My functional code for the telephone connection:</p>
  <pre><code>    class AuthenticateScreen extends StatefulWidget {
    @override
    _AuthenticateScreenState createState() =&gt; _AuthenticateScreenState();
  }
  
  class _AuthenticateScreenState extends State&lt;AuthenticateScreen&gt; {
    TextEditingController phoneController = TextEditingController();
    TextEditingController otpController = TextEditingController();
  
    FirebaseAuth auth = FirebaseAuth.instance;
    bool otpVisibility = false;
    User? user;
    String verificationID = &quot;&quot;;
    
    String phoneNumber = &quot;&quot;;
    final DocumentReference documentReference =
    FirebaseFirestore.instance.doc(&quot;users/{users}&quot;);
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(
            &quot;Phone Auth&quot;,
            style: TextStyle(
              fontSize: 30,
            ),
          ),
          backgroundColor: Colors.indigo[900],
        ),
        body: Container(
          margin: EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: phoneController,
                decoration: InputDecoration(
                  hintText: 'Phone Number',
                  prefix: Padding(
                    padding: EdgeInsets.all(4),
                    child: Text('+33'),
                  ),
                ),
                maxLength: 10,
                keyboardType: TextInputType.phone,
              ),
              Visibility(
                child: TextField(
                  controller: otpController,
                  decoration: InputDecoration(
                    hintText: 'OTP',
                    prefix: Padding(
                      padding: EdgeInsets.all(4),
                      child: Text(''),
                    ),
                  ),
                  maxLength: 6,
                  keyboardType: TextInputType.number,
                ),
                visible: otpVisibility,
              ),
              SizedBox(
                height: 10,
              ),
              MaterialButton(
                color: Colors.indigo[900],
                onPressed: () {
                  if (otpVisibility) {
                    verifyOTP();
                  } else {
                    loginWithPhone();
                  }
                },
                child: Text(
                  otpVisibility ? &quot;Verify&quot; : &quot;Login&quot;,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
  
    void loginWithPhone() async {
      auth.verifyPhoneNumber(
        phoneNumber: &quot;+33&quot; + phoneController.text,
        verificationCompleted: (PhoneAuthCredential credential) async {
          await auth.signInWithCredential(credential).then((value) {
            print(&quot;You are logged in successfully&quot;);
          });
        },
        verificationFailed: (FirebaseAuthException e) {
          print(e.message);
        },
        codeSent: (String verificationId, int? resendToken) {
          otpVisibility = true;
          verificationID = verificationId;
          setState(() {});
        },
        codeAutoRetrievalTimeout: (String verificationId) {},
      );
    }
  
    void verifyOTP() async {
      PhoneAuthCredential credential = PhoneAuthProvider.credential(
          verificationId: verificationID, smsCode: otpController.text);
  
  
      await auth.signInWithCredential(credential).then(
            (value) {
          setState(()  {
            phoneNumber = phoneController.text;
            print(&quot;Connecte avec le compte &quot; + &quot;+33&quot; + phoneController.text,);
            user = FirebaseAuth.instance.currentUser;
  
          });
        },
      ).whenComplete(
            () {
  
          if (user != null) {
  
            Fluttertoast.showToast(
              msg: &quot;Vous êtes maintenant connecté&quot;,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 1,
              backgroundColor: Blue2Color,
              textColor: Colors.white,
              fontSize: 16.0,
            );
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) =&gt; Home_Screen(),
              ),
            );
          } else {
            Fluttertoast.showToast(
              msg: &quot;La connexion a échoué.&quot;,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.BOTTOM,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.red,
              textColor: Colors.white,
              fontSize: 16.0,
            );
          }
        },
      );
    }
  }
  </code></pre>
  <p>And here is my old code for login by mail to create a collection on firestore database :</p>
  <pre><code>class AuthenticationService {
    final FirebaseAuth _auth = FirebaseAuth.instance;
  
    AppUser? _userFromFirebaseUser(User? user) {
      initUser(user);
      return user != null ? AppUser(user.uid) : null;
    }
  
    void initUser(User? user) async {
      if(user == null) return;
      NotificationService.getToken().then((value) {
        DatabaseService(user.uid).saveToken(value);
      });
    }
  
    Stream&lt;AppUser?&gt; get user {
      return _auth.authStateChanges().map(_userFromFirebaseUser);
    }
  
    Future signInWithEmailAndPassword(String email, String password) async {
      try {
        UserCredential result =
        await _auth.signInWithEmailAndPassword(email: email, password: password);
        User? user = result.user;
  
  
  
        return _userFromFirebaseUser(user);
      } catch (exception) {
        print(exception.toString());
        return null;
      }
    }
  </code></pre>