简体   繁体   中英

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:

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 :

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. 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? 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.

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(),
          );
        }
      },
    );
  }
}

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