Невозможно получить данные от будущего провайдера, содержащие основную базу данных PhoneAutherisation - PullRequest
0 голосов
/ 26 апреля 2020

Чтобы абстрагировать код, я использовал FutureProvider для проверки подлинности телефона с помощью firebase. Я сделал что-то не так, но если кто-то может помочь мне добиться того же с его / ее кодом, будет очень признателен.

Это основной код:

Future<void> main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        FutureProvider<VerificationProvider>(
          create: (context) => VerificationProvider().verifyPhone().catchError(
            (e) {
              print(e);
            },
          ),
        )
      ],
      child: MaterialApp(
        home: Delete(),
        routes: {
          Delete.id: (context) => Delete(),
        },
      ),
    );
  }
}

Это класс для обеспечения аутентификации с использованием провайдера:

class VerificationProvider with ChangeNotifier {
  FirebaseAuth _auth = FirebaseAuth.instance;
  String _verificationCode;
  String _phoneNo;
  FirebaseUser _user;

  void setPhoneNo(String phone) {
    _phoneNo = phone;
    notifyListeners();
  }

  void setVerificationCode(String code) {
    _verificationCode = code;
    notifyListeners();
  }

  FirebaseUser getUser() {
    return _user;
  }

  Future<void> verifyPhone() async {
    final PhoneCodeAutoRetrievalTimeout _autoRetrievalTimeout = (String verId) {
      print("auto verification executed");
    };

    final PhoneCodeSent _smsCodeSent = (String verId, [int forceCodeResend]) {
      AuthCredential _authCredentials = PhoneAuthProvider.getCredential(
          verificationId: verId, smsCode: _verificationCode);
      print("smsCodeSent Executed");
    };
    final PhoneVerificationCompleted _verificationCompleted =
        (AuthCredential _authCredentials) async {
      AuthResult result = await _auth.signInWithCredential(_authCredentials);
      _user = result.user;
      print("Logged in user is ${_user.phoneNumber}");
      print("phone verification completed");
    };
    final PhoneVerificationFailed _phoneVerificationFailed = (AuthException e) {
      print("phone verifiaction failed");
      print(e.message);
    };
    await _auth.verifyPhoneNumber(
      phoneNumber: _phoneNo,
      timeout: const Duration(seconds: 15),
      verificationCompleted: _verificationCompleted,
      verificationFailed: _phoneVerificationFailed,
      codeSent: _smsCodeSent,
      codeAutoRetrievalTimeout: _autoRetrievalTimeout,
    );
  }
}

И в этом виджете я пытаюсь использовать его .

class Delete extends StatefulWidget {
  static String id = "Delete";
  @override
  _DeleteState createState() => _DeleteState();
}

class _DeleteState extends State<Delete> {
  String phoneNo;
  @override
  Widget build(BuildContext context) {
    var test = Provider.of<void>(context);  **//after adding this line i am getting error**
    return Scaffold(
      backgroundColor: Colors.orange,
      body: Center(
        child: Text("hu"),
      ),
    );
  }
}

Ошибка: не удалось найти правильного поставщика над этим виджетом удаления

1 Ответ

0 голосов
/ 27 апреля 2020

Вы можете поместить MultiProvider в main()
Вы можете сослаться на официальный документ https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple#changenotifierprovider

фрагмент кода

Future<void> main() async {
  runApp(
    MultiProvider(
      providers: [
        FutureProvider(
          create: (context) => VerificationProvider().verifyPhone().catchError(
            (e) {
              print(e);
            },
          ),
        )
      ],
      child: MyApp(),
    ),
  );
}

полный код теста

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

Future<void> main() async {
  runApp(
    MultiProvider(
      providers: [
        FutureProvider(
          create: (context) => VerificationProvider().verifyPhone().catchError(
            (e) {
              print(e);
            },
          ),
        )
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Delete(),
      routes: {
        Delete.id: (context) => Delete(),
      },
    );
  }
}

class VerificationProvider with ChangeNotifier {
  FirebaseAuth _auth = FirebaseAuth.instance;
  String _verificationCode;
  String _phoneNo;
  FirebaseUser _user;

  void setPhoneNo(String phone) {
    _phoneNo = phone;
    notifyListeners();
  }

  void setVerificationCode(String code) {
    _verificationCode = code;
    notifyListeners();
  }

  FirebaseUser getUser() {
    return _user;
  }

  Future<void> verifyPhone() async {
    final PhoneCodeAutoRetrievalTimeout _autoRetrievalTimeout = (String verId) {
      print("auto verification executed");
    };

    final PhoneCodeSent _smsCodeSent = (String verId, [int forceCodeResend]) {
      AuthCredential _authCredentials = PhoneAuthProvider.getCredential(
          verificationId: verId, smsCode: _verificationCode);
      print("smsCodeSent Executed");
    };
    final PhoneVerificationCompleted _verificationCompleted =
        (AuthCredential _authCredentials) async {
      AuthResult result = await _auth.signInWithCredential(_authCredentials);
      _user = result.user;
      print("Logged in user is ${_user.phoneNumber}");
      print("phone verification completed");
    };
    final PhoneVerificationFailed _phoneVerificationFailed = (AuthException e) {
      print("phone verifiaction failed");
      print(e.message);
    };
    await _auth.verifyPhoneNumber(
      phoneNumber: _phoneNo,
      timeout: const Duration(seconds: 15),
      verificationCompleted: _verificationCompleted,
      verificationFailed: _phoneVerificationFailed,
      codeSent: _smsCodeSent,
      codeAutoRetrievalTimeout: _autoRetrievalTimeout,
    );
  }
}

class Delete extends StatefulWidget {
  static String id = "Delete";
  @override
  _DeleteState createState() => _DeleteState();
}

class _DeleteState extends State<Delete> {
  String phoneNo;
  @override
  Widget build(BuildContext context) {
    var test = Provider.of<void>(context);
    return Scaffold(
      backgroundColor: Colors.orange,
      body: Center(
        child: Text("hu"),
      ),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...