Проверка подлинности телефона с использованием firebase на флаттере не работает - PullRequest
1 голос
/ 17 января 2020

Это код для моей страницы входа в систему

// 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'

Я уже добавил отпечаток SHA в свой проект Firebase, и когда я нажимаю кнопку Кнопка, которая вызывает функцию, я использую строку, чтобы указать, действительно ли она запущена или нет, и хотя строка показала «Отправлено кода», на мой телефон не было отправлено никакого действительного кода. Опять же, я действительно неопытный и очень ценю вашу помощь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...