'The named parameter 'email is required, but there's no corresponding argument

I've a problem with this kind of bug and I hope someone can please tell me how to fix it.

The code:

import 'package:flutter/material.dart';
import 'package:login_form/model/login_model.dart';

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

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  GlobalKey<FormState> globalFormKey = new GlobalKey<FormState>();
  bool hidePassword = true;
  LoginRequestModel requestModel;

  @override
  void initState() {
    super.initState();
    requestModel = new LoginRequestModel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: scaffoldKey,
        backgroundColor: Theme.of(context).accentColor,
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
                    margin: EdgeInsets.symmetric(vertical: 85, horizontal: 20),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: Theme.of(context).primaryColor,
                      boxShadow: [
                        BoxShadow(
                            color: Theme.of(context).hintColor.withOpacity(0.2),
                            offset: Offset(0, 10),
                            blurRadius: 20)
                      ],
                    ),
                    child: Form(
                      key: globalFormKey,
                      child: Column(
                        children: <Widget>[
                          SizedBox(
                            height: 25,
                          ),
                          Text(
                            "Login",
                            style: Theme.of(context).textTheme.headline2,
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          new TextFormField(
                            keyboardType: TextInputType.emailAddress,
                            onSaved: (input) => requestModel.email = input,
                            validator: (input) =>
                                !(input?.contains("@") ?? false)
                                    ? "Email id Should be valid"
                                    : null,
                            decoration: new InputDecoration(
                              hintText: "Email Address",
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: Theme.of(context)
                                    .accentColor
                                    .withOpacity(0.2),
                              )),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                      color: Theme.of(context).accentColor)),
                              prefixIcon: Icon(Icons.email,
                                  color: Theme.of(context).accentColor),
                            ),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          new TextFormField(
                            keyboardType: TextInputType.text,
                            onSaved: (input) => requestModel.password = input,
                            validator: (input) => (input != null &&
                                    input.length < 3)
                                ? "Password should be more than < 3 characters"
                                : null,
                            obscureText: hidePassword,
                            decoration: new InputDecoration(
                              hintText: "Password",
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: Theme.of(context)
                                    .accentColor
                                    .withOpacity(0.2),
                              )),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                      color: Theme.of(context).accentColor)),
                              prefixIcon: Icon(Icons.lock,
                                  color: Theme.of(context).accentColor),
                              suffixIcon: IconButton(
                                onPressed: () {
                                  setState(() {
                                    hidePassword = !hidePassword;
                                  });
                                },
                                icon: Icon(hidePassword
                                    ? Icons.visibility_off
                                    : Icons.visibility),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 30,
                          ),
                          TextButton(
                              child: Text(
                                "Login",
                                style: TextStyle(color: Colors.white),
                              ),
                              onPressed: () {
                                if (validateAndSave()) {
                                  print(requestModel.toJson());
                                }
                              },
                              style: TextButton.styleFrom(
                                  padding: EdgeInsets.symmetric(
                                    vertical: 12,
                                    horizontal: 80,
                                  ),
                                  backgroundColor:
                                      Theme.of(context).accentColor,
                                  shape: StadiumBorder())),
                        ],
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ));
  }

  bool validateAndSave() {
    final form = globalFormKey.currentState;
    if (form!.validate()) {
      form.save();
      return true;
    }
    return false;
  }
}

this is my Loginmodel.dart code

class LoginResponseModel {
  final String status;
  final String message;
  final String kid;
  final String uid;
  final String email;
  final String password;

  LoginResponseModel({
    required this.status, 
    required this.message, 
    required this.kid, 
    required this.uid, 
    required this.email,
    required this.password});


  factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
    return LoginResponseModel(
        status: json["status"] as String? ?? "",
        message: json["message"] as String? ?? "",
        kid: json["kid"] as String? ?? "",
        uid: json["uid"] as String? ?? "",
        email: json["email"] as String? ?? "",
        password: json["password"] as String? ?? "",
      );
  }
}

class LoginRequestModel {
  String email;
  String password;

  LoginRequestModel({
    required this.email,
    required this.password,
    });

  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {
      'email': email.trim(),
      'password': password.trim(),
    };
    return map;
  }
}

The error:

The Error On LoginRequestModel requestModel; says " Non Nullable Instance field 'requestModel' must be initialized.

Then Error message on requestModel = new LoginRequestModel() says The Named Parameter 'email is required, but there's no corresponding argument.

And Last On OnSaved = input says "A value of type 'String?' can't be assigned to a variable of type 'string'."

I really appreciate the answer you gave



Solution 1:[1]

The Error On LoginRequestModel requestModel; says " Non Nullable Instance field 'requestModel' must be initialized.

You need to change:

LoginRequestModel requestModel;

Into the following since you are first setting the value in initState and therefore the variable are not going to be given a value right away then the object is created:

late LoginRequestModel requestModel;

Then Error message on requestModel = new LoginRequestModel() says The Named Parameter 'email is required, but there's no corresponding argument.

I don't know the content of the class LoginRequestModel but I would guess it has a named parameter email which is required to be specified when calling the LoginRequestModel constructor.

And Last On OnSaved = input says "A value of type 'String?' can't be assigned to a variable of type 'string'."

Again, I don't know your LoginRequestModel class but I would guess the email field is not nullable. That is a problem since onSave expects a method with the signature:

void FormFieldSetter<T>(
    T? newValue
) 

So your code here does not take into account that input is a nullable variable:

onSaved: (input) => requestModel.email = input

Since some of your problems is related to issues with Dart null-safety I will recommend you to read: https://dart.dev/null-safety

Solution 2:[2]

One by One,

The first one, you defined LoginRequestModel requestModel as non-nullable by default means that this variable is declared normally cannot be null. more detail You could just change LoginRequestModel requestModel; to LoginRequestModel requestModel= new LoginRequestModel();, instead of giving a value in initState. It looks like

  LoginRequestModel requestModel = new LoginRequestModel();

  @override
  void initState() {
    super.initState();
    // requestModel = new LoginRequestModel();
  }

Or use late (It is expensive)

Second one, I think in LoginRequestModel will lool like this LoginRequestModel({@required this.email}). You can choose to remove @required or give a empty value.

Last one, since requestModel.password and requestModel.email is non-nullable, it should like onSaved: (input) => requestModel.email = input!;

Solution 3:[3]

I think this should fix your problem. In order to solve the error

  1. assign the value of requestModel at the time of declaring it instead of in initState.
  2. pass empty string as arguments to LoginRequestModel because email and password are required field.
  3. write input! instead of input to indicate that input is not null

import 'package:flutter/material.dart';
import 'package:login_form/model/login_model.dart';

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

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  GlobalKey<FormState> globalFormKey = new GlobalKey<FormState>();
  bool hidePassword = true;

  LoginRequestModel requestModel = new LoginRequestModel('','');

  @override
  void initState() {
    super.initState();
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: scaffoldKey,
        backgroundColor: Theme.of(context).accentColor,
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
                    margin: EdgeInsets.symmetric(vertical: 85, horizontal: 20),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: Theme.of(context).primaryColor,
                      boxShadow: [
                        BoxShadow(
                            color: Theme.of(context).hintColor.withOpacity(0.2),
                            offset: Offset(0, 10),
                            blurRadius: 20)
                      ],
                    ),
                    child: Form(
                      key: globalFormKey,
                      child: Column(
                        children: <Widget>[
                          SizedBox(
                            height: 25,
                          ),
                          Text(
                            "Login",
                            style: Theme.of(context).textTheme.headline2,
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          new TextFormField(
                            keyboardType: TextInputType.emailAddress,
                            onSaved: (input) => requestModel.email = input!,
                            validator: (input) =>
                                !(input?.contains("@") ?? false)
                                    ? "Email id Should be valid"
                                    : null,
                            decoration: new InputDecoration(
                              hintText: "Email Address",
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: Theme.of(context)
                                    .accentColor
                                    .withOpacity(0.2),
                              )),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                      color: Theme.of(context).accentColor)),
                              prefixIcon: Icon(Icons.email,
                                  color: Theme.of(context).accentColor),
                            ),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          new TextFormField(
                            keyboardType: TextInputType.text,
                            onSaved: (input) => requestModel.password = input!,
                            validator: (input) => (input != null &&
                                    input.length < 3)
                                ? "Password should be more than < 3 characters"
                                : null,
                            obscureText: hidePassword,
                            decoration: new InputDecoration(
                              hintText: "Password",
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                color: Theme.of(context)
                                    .accentColor
                                    .withOpacity(0.2),
                              )),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                      color: Theme.of(context).accentColor)),
                              prefixIcon: Icon(Icons.lock,
                                  color: Theme.of(context).accentColor),
                              suffixIcon: IconButton(
                                onPressed: () {
                                  setState(() {
                                    hidePassword = !hidePassword;
                                  });
                                },
                                icon: Icon(hidePassword
                                    ? Icons.visibility_off
                                    : Icons.visibility),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 30,
                          ),
                          TextButton(
                              child: Text(
                                "Login",
                                style: TextStyle(color: Colors.white),
                              ),
                              onPressed: () {
                                if (validateAndSave()) {
                                  print(requestModel.toJson());
                                }
                              },
                              style: TextButton.styleFrom(
                                  padding: EdgeInsets.symmetric(
                                    vertical: 12,
                                    horizontal: 80,
                                  ),
                                  backgroundColor:
                                      Theme.of(context).accentColor,
                                  shape: StadiumBorder())),
                        ],
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ));
  }

  bool validateAndSave() {
    final form = globalFormKey.currentState;
    if (form!.validate()) {
      form.save();
      return true;
    }
    return false;
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 julemand101
Solution 2 Sam Chan
Solution 3 Abrar Malek