简体   繁体   English

我应该将谷歌登录变量传递给其他 class 吗?

[英]Should I pass the google sign-in variables to other class?

I made a log-in page and made a button for google log-in like this:我制作了一个登录页面并制作了一个用于谷歌登录的按钮,如下所示:

Future<String> login_google() async{
  FirebaseAuth auth = FirebaseAuth.instance;
  GoogleSignIn googleSignIn = GoogleSignIn();
  GoogleSignInAccount? account = await googleSignIn.signIn();
  GoogleSignInAuthentication authentication = await account!.authentication;
  AuthCredential credential = GoogleAuthProvider.credential(
      idToken: authentication.idToken,
      accessToken: authentication.accessToken);

  final authResult = await auth.signInWithCredential(credential);
  final user = authResult.user;

  print (user?.uid);
  print (user?.email);
  print('google log-in completed');
  return Future.value(user?.uid);
}


...


class _login_pageState extends State<login_page> {
  @override
  Widget build(BuildContext context) {
//    String uid_r = await login_google();
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          toolbarHeight: 1.0,
        ),
        body:Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image( image: AssetImage('asset/logo.png'),),
            ElevatedButton(onPressed: (){
              login_kakao();
              Navigator.of(context).push(MaterialPageRoute(builder: (context) =>main_bone(uid:'')));
            }, child: Text('Kakao Log-In')),
            ElevatedButton(onPressed: (){
//              login_kakao();
            final uid = login_google().then(
                (value){
                  Navigator.of(context).push(MaterialPageRoute(builder: (context) =>main_bone(uid: value))); => The button for LOG-IN .
                }
            );
            }, child: Text('Google Log-In'))

          ],
        ),

    );
  }
}

Here I succeeded in log-in and passed only uid thinking that only uid is required.在这里,我成功登录并仅传递了uid,认为只需要uid。 And My firestore rules for accessing is following:我的firestore访问规则如下:

 match /post/{document=**} 
    {
      allow read;
      allow write:if
      auth.uid != null; 
    }

On the next page, None of the data in collection(post) were shown, which means the log in has disabled on the next class.在下一页上,没有显示 collection(post) 中的数据,这意味着在下一个 class 上已禁用登录。

Should I pass the whole variables for authentication to next class, for example, auth, credential?我是否应该将用于身份验证的整个变量传递给下一个 class,例如身份验证、凭据?

its called inherited widget, there is a lot method to make your entire app authenticated, not just one class.它称为继承的小部件,有很多方法可以使您的整个应用程序经过身份验证,而不仅仅是一个 class。 make a stream builder, listen firebase_auth.authStateChanges()制作一个 stream 构建器,听 firebase_auth.authStateChanges firebase_auth.authStateChanges()

or you can use a package ( state management ): like flutter_bloc or或者您可以使用 package ( state 管理):如flutter_bloc

i prefer goRouter我更喜欢goRouter

check this video, its chris itself explain how to use it , its even better;查看这个视频,它的克里斯本身解释了如何使用它,它甚至更好; work at flutter web too也在 flutter web 工作

take look at mine for your reference:看看我的供您参考:

import 'dart:ui';
import 'package:cms_prototype/auth/auth.dart';
import 'package:cms_prototype/home/home.dart';
import 'package:cms_prototype/login/login.dart';
import 'package:cms_prototype/theme.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';


Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      options: const FirebaseOptions(
          apiKey: "********",
          authDomain: "",
          appId: "",
          measurementId: "",
          storageBucket: "**.com",
          messagingSenderId: "**",
          projectId: "**"));

  final auth = AuthRepo();
  await auth.user.first;

  final router = GoRouter(

      urlPathStrategy: UrlPathStrategy.path,
      redirect: (GoRouterState state){
        if(auth.currentUser.isEmpty && state.location != '/login'){
          return '/login';
        }
        if(auth.currentUser.isNotEmpty && state.location == '/login'){
          return '/';
        }
        return null;
      },
      refreshListenable: GoRouterRefreshStream(auth.user),
      routes: [
        GoRoute(
            name: 'home',
            path: '/',
            pageBuilder: (context, state) => MaterialPage(
                key: state.pageKey,
                child: const HomePage())),
        GoRoute(
            name: 'login',
            path: '/login',
            pageBuilder: (context, state) => MaterialPage(
                key: state.pageKey,
                child: LoginPage(authRepo: auth,))),
      ],
      errorPageBuilder: (context, state) => const MaterialPage(
          child: Scaffold(
            body: Center(
              child: Text("404 Error"),
            ),
          )));

  runApp(MyApp(router: router,authRepo: auth,));
}

class MyApp extends StatelessWidget {
  final GoRouter router;
  final AuthRepo authRepo;
  const MyApp({Key? key, required this.router, required this.authRepo}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {


    return MaterialApp.router(
      routeInformationProvider: router.routeInformationProvider,
      routeInformationParser: router.routeInformationParser,
      routerDelegate: router.routerDelegate,
      debugShowCheckedModeBanner: false,
      scrollBehavior: const MaterialScrollBehavior().copyWith(
        dragDevices: {
          PointerDeviceKind.mouse,
          PointerDeviceKind.touch,
          PointerDeviceKind.stylus,
          PointerDeviceKind.unknown
        },
      ),
      title: 'CMS Prototype',
      theme: appTheme,
    );
  }
}

auth repo class: ---->授权仓库 class:---->

class AuthRepo {

  final AuthCache _cache;
  final firebase_auth.FirebaseAuth _firebaseAuth;
  final GoogleSignIn _googleSignIn;

  AuthRepo({AuthCache? cache, firebase_auth.FirebaseAuth? firebaseAuth, GoogleSignIn? googleSignIn})
  : _cache = cache?? AuthCache(),
  _firebaseAuth = firebaseAuth ?? firebase_auth.FirebaseAuth.instance,
  _googleSignIn = googleSignIn ?? GoogleSignIn.standard();

  Stream<User> get user {
    return _firebaseAuth.authStateChanges().map((fUser){
     final user = fUser == null ? User.empty : fUser.toUser;
     _cache.write(key: user.id, value: user);
     return user;
    });
  }

  User get currentUser {
    final key = _firebaseAuth.currentUser != null? _firebaseAuth.currentUser!.uid : '';
    return _cache.read(key: key) ?? User.empty;
  }

  Future<void> signUp({required String email, required String password}) async {
    try {
      await _firebaseAuth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
    } on firebase_auth.FirebaseAuthException catch (e) {
      throw SignUpWithEmailAndPasswordFailure.fromCode(e.code);
    } catch (_) {
      throw const SignUpWithEmailAndPasswordFailure();
    }
  }

  //login with google (GOOGLE SIGN IN)
  Future<void> loginWithGoogle() async {
    try {
      late final firebase_auth.AuthCredential credential;
      if(kIsWeb){
        final googleProvider = firebase_auth.GoogleAuthProvider();
        final userCredential = await _firebaseAuth.signInWithPopup(googleProvider);
        credential = userCredential.credential!;

      }else{
        final googleUser = await _googleSignIn.signIn();
        final googleAuth = await googleUser!.authentication;
        credential = firebase_auth.GoogleAuthProvider.credential(
          accessToken: googleAuth.accessToken,
          idToken: googleAuth.idToken
        );
      }

      await _firebaseAuth.signInWithCredential(credential);
    }
    on firebase_auth.FirebaseAuthException catch (e){
      throw LogInWithGoogleFailure.fromCode(e.code);
    }
    catch (e){
      throw const LogInWithGoogleFailure();
    }
  }

  //email dan password

  Future<LogInWithEmailAndPasswordFailure?> loginWithEmailAndPassword ({required String email, required String password}) async{
    try{
      await _firebaseAuth.signInWithEmailAndPassword(
          email: email,
          password: password
      );
    }
    on firebase_auth.FirebaseAuthException catch (e){
      //return e.code;
      return LogInWithEmailAndPasswordFailure.fromCode(e.code);
    }
    catch (_){

      //return 'masalah jaringan terdeteksi';
      return const LogInWithEmailAndPasswordFailure();
    }
    return null;
  }

  Future<void> logOut() async {
    try {
      await Future.wait([
        _firebaseAuth.signOut(),
        _googleSignIn.signOut(),
      ]);
    } catch (_) {
      throw LogOutFailure();
    }
  }

}

You should be able to access all the data for the current user using FirebaseAuth.instance.currentUser .您应该能够使用FirebaseAuth.instance.currentUser访问当前用户的所有数据。 Use that to access the current user and pass any data to backend using that user's credentials and token.使用它来访问当前用户并使用该用户的凭据和令牌将任何数据传递到后端。

final user = FirebaseAuth.instance.currentUser;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter Google 登录不工作平台异常 - Flutter Google Sign-In not working platformexception 我的 Flutter 应用程序中的 Google 登录失败 - Google sign-in is failing in my Flutter app 返回 RESULT_CANCELED 的 Google 登录片段 - Google sign-in fragment returning RESULT_CANCELED 如何将动态 IP 地址添加到 Google Cloud 中的“授权 javascript 来源”列表中,以便将 Google 登录集成到我的 web 应用程序中? - How can I add a dynamic IP address to the "Authorised javascript origins" list in Google Cloud so that I can integrate Google sign-in into my web app? AWS-Amplify,如何在角度登录后重定向到另一个 URL? - AWS-Amplify, How do I redirect to another URL after sign-in in angular? 如何在没有 aws-auth configmap 的情况下登录 EKS 集群? - How to sign-in to EKS cluster without aws-auth configmap? 谷歌使用 flutter 和 firebase auth 登录 - google sign in with flutter and firebase auth RN Firebase:在手机上请求无密码登录,在 PC 上打开链接,在手机上登录? - RN Firebase: Request passwordless sign-in on mobile, open link on PC, get signed-in on mobile? 为什么使用 Firebase 登录 Google 对我不起作用? - Why Sign In With Google using Firebase not work with me? Android FirebaseUI 使用 Google 登录时释放密钥错误 - Android FirebaseUI sign in with Google error for release key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM