简体   繁体   English

如何将 Firebase 身份验证添加到 Flutter?

[英]How to add Firebase Authentication to Flutter?

The official docs for Firebase Authentication for Flutter mentions this code to check whether user is logged in or not: Firebase Authentication for Flutter 的官方文档提到了这个代码来检查用户是否登录:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

Docs also mention that Firebase must be initialized before anything else so I have added the initialization code to main.dart :文档还提到 Firebase 必须先初始化,所以我已将初始化代码添加到main.dart

class MyApp extends StatelessWidget {
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          // Handle error
        }
        if (snapshot.connectionState == ConnectionState.done) {
          return AuthState();
        }
        return CircularProgressIndicator();
      },
    );
  }
}

AuthState is where I want to manage the authentication state. AuthState是我要管理身份验证 state 的地方。 I have added it in the same file.我已将其添加到同一个文件中。

class AuthState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auth',
      home: FirebaseAuth.instance.authStateChanges().listen((User user) {
        if (user == null) {
          return SignupScreen();
        } else {
          return HomeScreen();
        }
      }),
    );
  }
}

The above code does not work because home expects a widget and authStateChanges returns StreamSubscription so how to make it work?上面的代码不起作用,因为home需要一个小部件并且authStateChanges返回StreamSubscription那么如何使其工作? I want to redirect to signup screen if user is not authenticated and to the home screen if user is.如果用户未通过身份验证,我想重定向到注册屏幕,如果用户是,我想重定向到主屏幕。

You could use a StreamBuilder to consume the stream of authentication state changes.您可以使用StreamBuilder来使用身份验证 state 更改的 stream。

import 'package:flutter/material.dart';

class AuthWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _AuthWidgetState createState() => _AuthWidgetState();
}

class _AuthWidgetState extends State<AuthWidget> {
  Widget build(BuildContext context) {
    return StreamBuilder<User>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          if (snapshot.data == null) {
            return SignupScreen();
          } else {
            return HomeScreen();
          }
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }
}

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

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