0

While trying to retreive authentication data from firebase, I am facing the error : The getter 'email' was called on null. Receiver: null Tried calling: email

even if this is no error in my code.

when the user sign in he will be redirected to home page:

Here is the code i am using home.dart (in which there is sidebar):

import 'package:flutter/material.dart';
import 'package:testa/bloc/navigation_bloc/navigation_bloc.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:testa/sidebar/sidebar.dart';
import 'package:testa/sidebar/sidebar_layout.dart';

class HomePage extends StatelessWidget with NavigationStates {

  const HomePage({Key key,@required this.user}) : super(key: key);
  final FirebaseUser user;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Home ${user.email}'),
      ),
      body: StreamBuilder<DocumentSnapshot>(
        stream: Firestore.instance
            .collection('/users')
            .document(user.uid)
            .snapshots(),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.hasError) {
            return Text('Error: ${snapshot.error}');
          } else if (snapshot.hasData) {
            return checkRole(snapshot.data);
          }
          return LinearProgressIndicator();
        },
      ),
    );

  }

  Center checkRole(DocumentSnapshot snapshot) {
    if (snapshot.data == null) {
      return Center(
        child: Text('no data set in the userId document in firestore'),
      );
    }
    if (snapshot.data['role'] == 'admin') {
      return adminPage(snapshot);
    } else {
      return userPage(snapshot);
    }
  }

  Center adminPage(DocumentSnapshot snapshot) {
    return Center(
        child: Text('${snapshot.data['role']} ${snapshot.data['name']}'));
  }

  Center userPage(DocumentSnapshot snapshot) {
    return Center(child: Text(snapshot.data['name']));
  }
}

Here is the code of sign_in.dart if it might help even if it seems there is no issue there

import 'package:firebase_auth/firebase_auth.dart';
import 'package:testa/pages/home.dart';
import 'package:flutter/material.dart';
import 'package:testa/sidebar/sidebar_layout.dart';
import 'package:testa/sidebar/sidebar.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => new _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _email, _password;


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                validator: (input) {
                  if(input.isEmpty){
                    return 'Provide an email';
                  }
                },
                decoration: InputDecoration(
                    labelText: 'Email'
                ),
                onSaved: (input) => _email = input,
              ),
              TextFormField(
                validator: (input) {
                  if(input.length < 6){
                    return 'Longer password please';
                  }
                },
                decoration: InputDecoration(
                    labelText: 'Password'
                ),
                onSaved: (input) => _password = input,
                obscureText: true,
              ),
              RaisedButton(
                onPressed: signIn,
                child: Text('Sign in'),
              ),
            ],
          )
      ),
    );
  }

  void signIn() async {
    if(_formKey.currentState.validate()){
      _formKey.currentState.save();
      try{
       FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password)).user;
       Navigator.push(context, MaterialPageRoute(builder: (context) => SideBarLayout(user: user)));

      }catch(e){
        print(e.message);
      }
    }
  }
}

when i change SideBarLayout by HomePage, it works fine, otherwise, i have an error under the first 'user' (context) => HomePage(user: user,))); and it says (the named parameter 'user' is not defined

  void signIn() async {
    if(_formKey.currentState.validate()){
      _formKey.currentState.save();
      try{
       FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password)).user;
        Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage(user: user,)));

      }catch(e){
        print(e.message);
      }
    }
  }

SideBarLayout.dart code:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'sidebar.dart';
import 'package:testa/bloc/navigation_bloc/navigation_bloc.dart';

class SideBarLayout extends StatelessWidget {


  const SideBarLayout({Key key, this.user}) : super(key: key);
 final FirebaseUser user;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocProvider<NavigationBloc>(
        create: (context) => NavigationBloc(),
        child: Stack(
          children: <Widget>[
            BlocBuilder<NavigationBloc, NavigationStates> (
              builder: (context, navigationState) {
                return navigationState as Widget;
              },
            ),
            SideBar(),

          ],
        ),
      ),
    );
  }
}
  • the email/password is correctn because firstly i sign up and the email is well stored in database, but just after it returns this error! – yassine zagliz May 22 '20 at 16:53
  • In the try-catch block of signInMethod try to print your email. As it seems your email filed is empty when you are passing data.put print(_email); at the start of try block . Check console and response to this comment with what you see in the console. – UTKARSH Sharma May 22 '20 at 16:55
  • Where is your `SiderBarLayout`, it is same as the `HomePage`? – Adnan karim May 22 '20 at 16:59
  • i have added that in this method and it shows me the email i used to log in and the same error again => Navigator.push(context, MaterialPageRoute(builder: (context) => SideBarLayout(user: user))); print('Home ${user.email}');// line added in the method }catch(e){ print(e.message); } } – yassine zagliz May 22 '20 at 17:03
  • @Adnankarim, its another class, so its not HomePage – yassine zagliz May 22 '20 at 17:05
  • Please edit your question and add the `SideBarLayout` class – Brendan May 22 '20 at 21:38
  • @UTKARSHSharma printing `user.email` is of no use because the error indicates that the `FirebaseUser` object is `null`, not the email property. – Christopher Moore Jul 14 '20 at 19:57

2 Answers2

0

Probably this error is caused by invalid email/password and the FirebaseAuth is returning null and without checking you are Navigating to the next page and hence it throws an error.

  1. Make sure you are providing correct credentials.
  2. Before navigating to the Homepage check if the user is null or not?

FirebaseUser user = (await FirebaseAuth.instance.signInWithEmailAndPassword(email: _email, password: _password)).user;
if(user!=null){
  // Navigate to Homepage
}
Adnan karim
  • 1,009
  • 10
  • 15
-1

Your user data is not being passed to the HomePgae, first convert your HomePgae to StatfullWidget Then make sure to add a constructor Check this how to pass data to a StatfullWidget Passing data to StatefulWidget and accessing it in it's state in Flutter

Ridha Rezzag
  • 3,672
  • 1
  • 34
  • 39
  • i converted this class to StatfullWidget, but i am not sure i understood the second step you have mentionned (make sure to add a constructor) even if i checked the link. thanks – yassine zagliz May 22 '20 at 22:00
  • I think its better to watch a video as its confusing little bit check this video at the minute 6:30 but i advice you to watch the whole video https://youtu.be/d5PpeNb-dOY – Ridha Rezzag May 23 '20 at 03:45
  • @RidhaRezzag It's not necessary to change this to a stateful widget. `HomePage` doesn't have anything that would require `State`. – Christopher Moore Jul 14 '20 at 19:59