Search code examples
flutterfirebasedartfirebase-authenticationdart-null-safety

future: FirebaseAuth.instance.currentUser(), throws an error, need alternatives


I have seen various questions about the same topic, and realized that 'currentUser' does not go with future after the update in FirebaseAuth

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<void> _logout() async {
    try {
      await FirebaseAuth.instance.signOut();
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Phone Auth Demo"),
        backgroundColor: Colors.cyan,
      ),
      body: FutureBuilder(
        future: FirebaseAuth.instance.currentUser(),
        builder: (context, snapshot) {
         final firebaseUser = snapshot.data;
          return snapshot.hasData
              ? Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "SignIn Success 😊",
                  style: TextStyle(
                    color: Colors.green,
                    fontWeight: FontWeight.bold,
                    fontSize: 30,
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                Text("UserId:${firebaseUser.uid}"),
                SizedBox(
                  height: 20,
                ),
                Text(
                    "Registered Phone Number: ${firebaseUser.phoneNumber}"),
                SizedBox(
                  height: 20,
                ),
                RaisedButton(
                  onPressed: _logout,
                  child: Text(
                    "LogOut",
                    style: TextStyle(color: Colors.white),
                  ),
                  color: Colors.cyan,
                )
              ],
            ),
          )
              : CircularProgressIndicator();
        },
      ),
    );
  }
}

future: FirebaseAuth.instance.currentUser(),

  • this line is the error. It shows this error:
  • The function can't be unconditionally invoked because it can be 'null'. (Documentation) Try adding a null check ('!').

Also, have some errors in uid and phoneNumber

  • There I have this error:
  • The property 'phoneNumber' can't be unconditionally accessed because the receiver can be 'null'. (Documentation) Try making the access conditional (using '?.') or adding a null check to the target ('!').

Solution

  • While you are using RaisedButton I will suggest you to update the flutter version. Now for getting current user, you dont need to use FutureBuilder, But make sure to initialize the Firebase on main method.

    You will get the current user with FirebaseAuth.instance.currentUser, it can return null,

    Here is the modification I've made,

    
    class _HomePageState extends State<HomePage> {
      Future<void> _logout() async {
        try {
          await FirebaseAuth.instance.signOut();
        } catch (e) {
          print(e.toString());
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("Phone Auth Demo"),
              backgroundColor: Colors.cyan,
            ),
            body: FirebaseAuth.instance.currentUser != null
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "SignIn Success 😊",
                          style: TextStyle(
                            color: Colors.green,
                            fontWeight: FontWeight.bold,
                            fontSize: 30,
                          ),
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        Text("UserId:${FirebaseAuth.instance.currentUser?.uid}"),
                        SizedBox(
                          height: 20,
                        ),
                        Text(
                            "Registered Phone Number: ${FirebaseAuth.instance.currentUser?.phoneNumber}"),
                        SizedBox(
                          height: 20,
                        ),
                        ElevatedButton(
                          onPressed: _logout,
                          child: Text(
                            "LogOut",
                            style: TextStyle(color: Colors.white),
                          ),
                        )
                      ],
                    ),
                  )
                : CircularProgressIndicator());
      }
    }