简体   繁体   中英

Flutter Riverpod 1.0: What provider to use for Firebase AuthService object?

I want to use Firebase Phone authentication for an Flutter app. I have an AuthService class and I need to expose getter codeSent to change a UI. Third party examples from official Riverpod's site are using other packages and not very clear. So how to use Riverod in this case?

import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  String _verificationId = '';
  int? _resendToken;
  bool _codeSent = false;

  Stream<User?> get user {
    return _auth.authStateChanges();
  }

  get currentUser {
    return _auth.currentUser;
  }

  Future verifyPhoneNumber(String phoneNumber) async {
    await _auth.verifyPhoneNumber(
        verificationCompleted: (PhoneAuthCredential credential) async {
          await _auth.signInWithCredential(credential);
        },
        verificationFailed: (FirebaseAuthException e) {
          if (e.code == 'invalid-phone-number') {
            print('The provided phone number is not valid.');
          }
        },
        codeSent: (String verificationId, int? resendToken) {
          _verificationId = verificationId;
          _resendToken = resendToken;
          _codeSent = true;
        },
        codeAutoRetrievalTimeout: (String verificationId) {
          _verificationId = verificationId;
        });
  }

  Future signWithOtp(String otp) async {
    PhoneAuthCredential credential = PhoneAuthProvider.credential(
        verificationId: _verificationId, smsCode: otp);
    await _auth.signInWithCredential(credential);
  }

  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (error) {
      print(error.toString());
      return null;
    }
  }
}

The problem was solved with ChangeNotifierProvider.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:aptekamall/service/auth.dart';

final authProvider = ChangeNotifierProvider<AuthService>((ref) {
  return AuthService();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM