在flutter上使用Firebase进行电话身份验证无法正常工作

时间:2020-01-17 17:20:58

标签: firebase flutter firebase-authentication password-less

这是我的sign_up页面的代码

// import 'dart:ff';

import 'dart:async';
import 'dart:developer';

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

class SignUpPage extends StatefulWidget {
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  TextEditingController phoneNumController = new TextEditingController();
  String _smsVerificationCode = "Null";
  String opTest = "Null";


  String errorMessage = '';
  void initSate() {
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: false,
        body: Column(
          children: <Widget>[
            Container(
              margin: const EdgeInsets.all(80),
              child: Column(
                children: <Widget>[
                  Align(
                    child: TextField(
                      controller: phoneNumController,
                      decoration: InputDecoration(
                          labelText: "Phone Number",
                          prefixText: "+855",
                          border: OutlineInputBorder()),
                    ),
                  ),
                  SizedBox(height: 20),
                  Align(
                      child: RaisedButton(
                    child: Text("VERIFY"),
                    elevation: 7.0,
                    onPressed: () => submit(context),
                  )),
                  SizedBox(height: 20),
                  Align(
                    child: RaisedButton(
                      child: Text("Test"),
                      elevation: 7.0,
                      onPressed: logP,
                    ),
                  ),
                  SizedBox(height: 20),
                  Align(child: Text(opTest))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void logP() {
    String phoneNum = "+855" + phoneNumController.text.toString();
    setState(() {
      opTest = phoneNum;
    });
  }

  void submit(BuildContext context) async {
    final FirebaseAuth _auth = FirebaseAuth.instance;
    String phoneNumber = "+855" + phoneNumController.text.toString();


    _verificationComplete(AuthCredential authCredential, BuildContext context) {
      _auth.signInWithCredential(authCredential).then((authResult) {
        final snackBar = SnackBar(
            content: Text("Success!!! UUID is: " + authResult.user.uid));
        Scaffold.of(context).showSnackBar(snackBar);
        setState(() {
          opTest = "Successful Authentication";
        });
      });
    }

    _verificationFailed(AuthException authException, BuildContext context) {
      final snackBar = SnackBar(
          content:
              Text("Exception!! message:" + authException.message.toString()));
      Scaffold.of(context).showSnackBar(snackBar);
      setState(() {
          opTest = "Failed Authentication";
        });
    }

    _smsCodeSent(String verificationId, List<int> code) {
      _smsVerificationCode = verificationId;
      setState(() {
          opTest = "Code Sent";
        });
    }

    _codeAutoRetrievalTimeout(String verificationId) {
      _smsVerificationCode = verificationId;
      setState(() {
          opTest = "Retrieval TimeOut";
        });
    }

    await _auth.verifyPhoneNumber(
        phoneNumber: phoneNumber,
        timeout: Duration(seconds: 60),
        verificationCompleted: (authCredential) =>
            _verificationComplete(authCredential, context),
        verificationFailed: (authException) =>
            _verificationFailed(authException, context),
        codeAutoRetrievalTimeout: (verificationId) =>
            _codeAutoRetrievalTimeout(verificationId),
        codeSent: (verificationId, [code]) =>
            _smsCodeSent(verificationId, [code]));
  }
}

我的build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.testing_flutter"
        minSdkVersion 18
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    implementation("com.google.android.gms:play-services-base:17.1.0")
    implementation("com.google.android.gms:play-services-places-placereport:17.0.0")
    implementation("com.google.android.gms:play-services-location:17.0.0")
    implementation("com.google.firebase:firebase-analytics:17.2.0")
    implementation("com.google.firebase:firebase-database-collection:17.0.0")
    implementation("com.google.firebase:firebase-common:18.0.0")
    implementation("com.google.firebase:firebase-auth-interop:18.0.0")
    implementation 'com.android.support:multidex:1.0.3'
    androidTestImplementation 'androidx.test:runner:1.3.0-alpha02'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha02'
}

apply plugin: 'com.google.gms.google-services'

我已经在我的Firebase项目中添加了SHA Fingerprint,并且当我单击触发该功能的按钮时,我使用String来指定它是否被实际触发,尽管该String显示为“已发送代码”,但没有实际代码已发送到我的手机。同样,我真的没有经验,也非常感谢您的帮助。

0 个答案:

没有答案