The method 'getUsers' was called on null. Receiver: null Tried calling: getUsers()

144 views Asked by At

I am getting error on red screen right after i run my app. My first screen is login screen. I want to simply register the user and login the user. but when i use the getUsers() or getLogin() I get the above error. I am fed up of this error. Searched everywhere but m not able to find any working solutions. Please can u please write the code which i need to add. Please help me. UserLogin.dart

import 'dart:ui';
import 'package:customer/models/registerUser.dart';
import 'package:customer/screens/UserRegistration.dart';
import 'package:customer/screens/people_list.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/form_helper.dart';
import 'package:flutter/material.dart';
import 'ForgotPassword.dart';


class UserLogin extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {

    return UserLoginState();
  }
}


class UserLoginState extends State<UserLogin>{
  final reguser = RegisterUser();
  String name,_password,_email;
  var _formKey=GlobalKey<FormState>();
  RegisterUser model;
  DBService dbService;
  var _minimumPadding = 5.0;
  TextEditingController usernameController=TextEditingController();
  TextEditingController passwordController=TextEditingController();
  bool isHiddenPassword=true;

  final scaffoldKey = new GlobalKey<ScaffoldState>();

  void _showSnackBar(String text) {
    scaffoldKey.currentState.showSnackBar(new SnackBar(
      content: new Text(text),
    ));
  }

  void _togglePasswordView() {
    setState(() {
      isHiddenPassword = !isHiddenPassword;
    });
  }
  @override
  Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: Text('Customer Tracking System'),),
          body:_fetchData(),
        );
    }
  Widget _fetchData(){
    return FutureBuilder<List<RegisterUser>>(
      future: dbService.getUsers(),
      builder:
          (BuildContext context, AsyncSnapshot<List<RegisterUser>> userDetails) {
        if (userDetails.hasData) {
          return _loginUI(userDetails.data);
        }

        return CircularProgressIndicator();
      },
    );
  }
    Widget _loginUI(List<RegisterUser> userDetails){
      TextStyle textStyle = Theme.of(context).textTheme.title;
      var height = MediaQuery.of(context).size.height;
      var width = MediaQuery.of(context).size.width;

      Form(
        key: _formKey,
        child: Container(

          child: Padding(
              padding: EdgeInsets.all(_minimumPadding * 2),

              child: ListView

                (
                children: <Widget>[
                  Text("Login".toUpperCase(),
                      style: TextStyle(
                          fontSize: 40.0, fontWeight: FontWeight.bold),

                      textAlign: TextAlign.center),
                  SizedBox(height: height * 0.08,),
                  Divider(),
                  Padding(
                      padding: EdgeInsets.only(
                          top: _minimumPadding * 3,
                          bottom: _minimumPadding),

                      child: TextFormField(
                          controller: usernameController,
                          style: textStyle,
                          validator: (String value) {
                            if (value.isEmpty) {
                              return 'Please Enter Name';
                            }
                            return null;
                          },
                          onSaved: (String value) {
                            _email = value;
                          },
                          decoration: InputDecoration(
                            // filled: true,
                            //fillColor: Colors.white,
                              prefixIcon: Icon(Icons.person),

                              labelText: 'Username',
                              hintText: 'Username',
                              border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0)
                              )
                          )
                      )),
                  Padding(
                      padding: EdgeInsets.only(
                          top: _minimumPadding * 3,
                          bottom: _minimumPadding),

                      child: TextFormField(
                          style: textStyle,
                          obscureText: isHiddenPassword,
                          controller: passwordController,
                          validator: (String value) {
                            if (value.isEmpty) {
                              return 'Please Enter Name';
                            }
                            return null;
                          },
                          onSaved: (String value) {
                            _password = value;
                          },
                          decoration: InputDecoration(
                              prefixIcon: Icon(Icons.lock),

                              suffixIcon: InkWell(
                                  onTap: _togglePasswordView,
                                  child: Icon(Icons.visibility)),
                              labelText: 'Password',
                              hintText: 'Password',
                              border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(25.0)
                              )
                          )
                      )
                  ),

                  InkWell(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ForgotPassword()));
                    },
                    child: Text(
                      "Forgot Password ?",
                      style: TextStyle(
                          fontSize: 18,
                          color: Colors.purpleAccent,

                          //fontWeight: FontWeight.bold,
                          letterSpacing: 1.7),
                      textAlign: TextAlign.right,
                    ),
                  ),
                  SizedBox(
                    height: height * 0.08,
                  ),
                  GestureDetector(
                    onTap: () {
                      _submit();
                    },
                    child: Container(
                      padding:
                      EdgeInsets.symmetric(horizontal: 26, vertical: 20),
                      decoration: BoxDecoration(
                        //gradient: new LinearGradient(
                        //colors: [Colors.purple, Colors.purpleAccent]),
                          color: Theme.of(context).primaryColor,

                          borderRadius: BorderRadius.circular(20),
                          boxShadow: [
                            BoxShadow(
                                blurRadius: 4,
                                //color: Colors.purpleAccent,
                                offset: Offset(2, 2))
                          ]),
                      child: Text(
                        "Login".toUpperCase(),
                        style: TextStyle(
                            fontSize: 20,
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            letterSpacing: 1.7),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),

                  SizedBox(
                    height: height * 0.05,
                  ),

                  SizedBox(
                    height: height * 0.05,
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                          child: Text("Not yet registered?",
                              style: TextStyle(
                                  fontSize: 25.0)
                          )
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) => UserRegistration()));
                        },

                        child: Center(
                          child: Container(
                            padding:
                            EdgeInsets.symmetric(
                                horizontal: 26, vertical: 10),
                            decoration: BoxDecoration(
                              //gradient: new LinearGradient(
                              // colors: [Colors.purple, Colors.purpleAccent]),
                                color: Theme.of(context).primaryColor,

                                borderRadius: BorderRadius.circular(20),
                                boxShadow: [
                                  BoxShadow(
                                      blurRadius: 4,
                                      //color:,
                                      offset: Offset(2, 2))
                                ]),
                            child: Text(
                              "Register".toUpperCase(),
                              style: TextStyle(
                                  fontSize: 20,
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  letterSpacing: 1.7),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              )),
        ),
      );

    }

  bool validateAndSave() {
    final form = _formKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }
  void _submit(){
    final form = _formKey.currentState;
    var res;
    if (validateAndSave()) {
      setState(() {
        //getLogin(_email, _password);
         res=dbService.getLogin(_email, _password).then((value) {
          if(res!=0){
          FormHelper.showMessage(
            context,
            "Login",
            "Login Successfull",
            "Ok",
                () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => People_List(),
                ),
              );
            },
          );}
          else {
            FormHelper.showMessage(
                context,
                "Login",
                "Login not Successfull",
                "Ok", () {}

            );
          }
        });
      });


  }
  }
  }

RegisterUser.dart

import 'model.dart';

class RegisterUser extends Model {
  static String table = 'userDetails';

  int id;
  String firstName;
  String lastName;
  String mobileNum;
  String emailId;
  String address;
  String userType;
  String password;


  RegisterUser({
    this.id,
    this.firstName,
    this.lastName,
    this.mobileNum,
    this.emailId,
    this.address,
    this.userType,
    this.password
  });

  static RegisterUser fromMap(Map<String, dynamic> map) {
    return RegisterUser(
      id: map["id"],
      firstName: map['firstName'].toString(),
      lastName: map['lastName'],
      mobileNum: map['mobileNum'],
      emailId: map['emailId'],
      address: map['address'],
      userType: map['userType'],
      password: map['password']
    );
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'id': id,
      'firstName': firstName,
      'lastName': lastName,
      'mobileNum': mobileNum,
      'emailId': emailId,
      'address': address,
      'userType':userType,
      'password':password
    };

    if (id != null) {
      map['id'] = id;
    }
    return map;
  }
}

db_service.dart

import 'package:customer/models/registerUser.dart';
import 'package:customer/utils/database_helper.dart';
Future<List<RegisterUser>> getUsers() async {
    await DB.init();
    List<Map<String, dynamic>> userDetails = await DB.query(RegisterUser.table);

    return userDetails.map((item) => RegisterUser.fromMap(item)).toList();
  }

  Future<List<RegisterUser>> getLogin(String email, String password) async {
    await DB.init();
    List<Map<String, dynamic>> res = await DB.rawQuery("SELECT * FROM userDetails WHERE emailId = '$email' and password = '$password'");

    if (res.length > 0) {
      return res.map((item) => RegisterUser.fromMap(item)).toList();
      //return new User.fromMap(res.first);
    }

    return null;
  }
2

There are 2 answers

0
Fathima Shafana On

I finally got the answer to my question. I had to just instantiate the DBService.
i.e DBService dbService=new DBService();

class UserLoginState extends State<UserLogin>{
  final reguser = RegisterUser();
  String name,_password,_email;
  var _formKey=GlobalKey<FormState>();
  RegisterUser model;
  DBService dbService=new DBService();
  ...
0
Gazihan Alankus On

You need a line with dbService = something before you can do dbService.getUsers() because just saying DbService dbService; initializes it to be null.

It's like a paper with no phone number on it and you are trying to call someone with it. You need to write down a phone number on it.