Home > OS >  TypeError: Cannot read properties of null (reading 'email')
TypeError: Cannot read properties of null (reading 'email')

Time:06-02

Someone know why I get this error? I am using final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); to get the text out of the textfields (password and email).

Then I use the signIn() methode with email: _emailController.text.trim(), password: _passwordController.text.trim() to get a string from the textfield. This informations are used to login the user.

The button login just use the methode signIn() and then the page dashboard is getting displayed. On the page dashboard there is a text with the email of the logged in user.

Why I am getting this error? Where have I done a mistake?

Error message:

======== Exception caught by widgets library =======================================================
The following JSNoSuchMethodError was thrown building DashboardView(dirty, state: _DashboardViewState#00d1f):
TypeError: Cannot read properties of null (reading 'email')

The relevant error-causing widget was: 
  DashboardView DashboardView:file:///C:/Users/Dennis/Documents/bestfitnesstrackereu/lib/routing/router.dart:25:28
When the exception was thrown, this was the stack: 
packages/bestfitnesstrackereu/pages/dashboard/dashboard_view.dart 50:1                                            build
packages/flutter/src/widgets/framework.dart 4922:27                                                               build

authentication.dart code: (login)

import 'package:bestfitnesstrackereu/routing/route_names.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthenticationPage extends StatefulWidget {
  const AuthenticationPage({Key key}) : super(key: key);

  @override
  State<AuthenticationPage> createState() => _AuthenticationPageState();
}

class _AuthenticationPageState extends State<AuthenticationPage> {
  bool checkBoxValue = false;
  //textfield controllers:
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();


  Future signIn() async{
    try {
      await FirebaseAuth.instance.signInWithEmailAndPassword(
          email: _emailController.text.trim(),
          password: _passwordController.text.trim()
      );
    } on FirebaseAuthException catch (e){
      print(e);
    }
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          constraints: BoxConstraints(maxWidth: 400),
          padding: EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
TextField(
                controller: _emailController,
                decoration: InputDecoration(
                  labelText: "E-Mail",
                  hintText: "[email protected]",
                    suffixIcon: Icon(Icons.mail_outline,),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20)
                  )
                ),
              ),

              SizedBox(height: 15,),

TextField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                    labelText: "Password",
                    hintText: "******",
                    suffixIcon: Icon(Icons.lock_outline, color: Colors.grey,),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20)
                    )
                ),
              ),
InkWell(
                onTap: (){
                  signIn();
                  Navigator.of(context).pushNamed(DashboardRoute);
                },
                child: Container(
                  decoration: BoxDecoration(color: Colors.deepPurple,
                  borderRadius: BorderRadius.circular(20)),
                  alignment: Alignment.center,
                  width: double.maxFinite,
                  padding: EdgeInsets.symmetric(vertical: 16),
                  child: Text(
                    "Login",
                    style: TextStyle(
                    color: Colors.white,
                  ),)
              )
              ),
 ],
          ),
        )
      ),
    );
  }
}

dashboard_view.dart code:

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

class DashboardView extends StatefulWidget {
  const DashboardView ({Key key}) : super(key: key);

  @override
  State<DashboardView> createState() => _DashboardViewState();
}

class _DashboardViewState extends State<DashboardView> {
  final user = FirebaseAuth.instance.currentUser;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment:  MainAxisAlignment.center,
          children: [
            Text('Dashboard View - signed in as '),
            SizedBox(height: 8,),
            Text(user.email),
            InkWell(
                onTap: () async {
                  await FirebaseAuth.instance.signOut();
                  print('user ist ausgeloggt');
                  //Navigator.of(context).pushNamed(AuthenticationPageRoute);
                },
                child: Container(
                    decoration: BoxDecoration(color: Colors.deepPurple,
                        borderRadius: BorderRadius.circular(20)),
                    alignment: Alignment.center,
                    width: double.maxFinite,
                    padding: EdgeInsets.symmetric(vertical: 16),
                    child: Text(
                      'sign out',
                      style: TextStyle(
                        color: Colors.white,
                      ),)
                )
            ),


          ],
        ),
    ),
    );
  }
}

CodePudding user response:

you are doing

onTap: (){
              signIn();
              Navigator.of(context).pushNamed(DashboardRoute);
            },

since you are not waiting for the signIn() method to be completed, you are already navigating to DashboardRoute and the _emailController is disposed.

That is why you are getting the issue.

Try and wait for the response from sign before navigating to next screen like

onTap: () async {
              await signIn();
              Navigator.of(context).pushNamed(DashboardRoute);
            },
  • Related