'getUsers' 方法在 null 上被调用。接收者:空尝试调用:getUsers()

时间:2021-05-05 07:14:56

标签: flutter sqflite database-connectivity

我在运行我的应用程序后立即在红屏上出现错误。我的第一个屏幕是登录屏幕。我想简单地注册用户并登录用户。但是当我使用 getUsers() 或 getLogin() 时,出现上述错误。我受够了这个错误。到处搜索,但找不到任何有效的解决方案。请你能写下我需要添加的代码吗?请帮我。 用户登录.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", () {}

            );
          }
        });
      });


  }
  }
  }

注册用户.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 个答案:

答案 0 :(得分:1)

在执行 auto m1_view = [&](){ if constexpr (N1 == 1) { return MatrixView<U, 2>({1, m1.dims[0]}, m1.dataView(), {m1.dims[0], 1}); } else { return MatrixView<U, N1>(m1); } }(); // notice extra () to immediate call auto m2_view = [&](){ if constexpr (N2 == 1) { return MatrixView<V, 2>({m2.dims[0], 1}, m2.dataView(), {1, 1}); } else { return MatrixView<V, N2>(m2); } }(); Matrix<T, N> res = zeros<T, N>(dims); res.applyFunctionWithBroadcast(m1_view, m2_view, MatmulTo<U, V, T, std::min(std::max(N1, 2lu), N - 1), std::min(std::max(N2, 2lu), N - 1), N - 1>); return res; 之前,您需要一行包含 dbService = something 的内容,因为只需说 dbService.getUsers() 就将其初始化为 null。

这就像一张纸上没有电话号码,而您正试图用它给某人打电话。您需要在上面写下电话号码。

答案 1 :(得分:0)

我的问题终于有了答案。 我只需要实例化 DBService。 即 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();
  ...