Riverpod 2.5 和 Firebase

问题描述 投票:0回答:1

我目前正在使用 Riverpod 2.5 和 Google Sign-In,并且正在尝试找出如何将 Riverpod 与其集成。 Riverpod 2.5 建议不要使用 StateProvider 和 ChangeNotifier。有趣的是,他们文档中的所有示例仍然使用旧版本的 Riverpod!

Riverpod 和 Firebase 的最佳实践是什么(例如 Google 登录和电子邮件)?

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

part 'firebase_service.g.dart';

class FirebaseAuthServices extends _FirebaseAuthServices {
  @riverpod
  Future<UserCredential> signInWithGoogle() async {
    // Trigger the authentication flow
    final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

    // Obtain the auth details from the request
    final GoogleSignInAuthentication? googleAuth =
        await googleUser?.authentication;

    // Create a new credential
    final credential = GoogleAuthProvider.credential(
      accessToken: googleAuth?.accessToken,
      idToken: googleAuth?.idToken,
    );

    // Once signed in, return the UserCredential
    return await FirebaseAuth.instance.signInWithCredential(credential);
  }
}
flutter riverpod
1个回答
0
投票

Claude Ai 帮助了我,但我想知道是否有更好的方法?

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

// This line is necessary for code-generation to work
part 'firebase_auth_notifier.g.dart';

@riverpod
class FirebaseAuthNotifier extends _$FirebaseAuthNotifier {
  @override
  FutureOr<User?> build() {
    // Return the current user, or null if not signed in
    return FirebaseAuth.instance.currentUser;
  }

  Future<void> signInWithGoogle() async {
    state = const AsyncLoading();

    try {
      // Trigger the authentication flow
      final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

      if (googleUser == null) {
        state = const AsyncData(null);
        return;
      }

      // Obtain the auth details from the request
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

      // Create a new credential
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Sign in to Firebase with the Google credential
      final userCredential = await FirebaseAuth.instance.signInWithCredential(credential);

      state = AsyncData(userCredential.user);
    } catch (e, stackTrace) {
      state = AsyncError(e, stackTrace);
    }
  }

  Future<void> signOut() async {
    await FirebaseAuth.instance.signOut();
    state = const AsyncData(null);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.