【问题标题】:The named parameter 'email is required, but there's no corresponding argument命名参数 'email 是必需的,但没有对应的参数
【发布时间】:2021-07-09 08:48:04
【问题描述】:

我遇到了这种错误,希望有人能告诉我如何修复它。

代码:

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;
  }
}

这是我的 Loginmodel.dart 代码

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;
  }
}

错误:

LoginRequestModel requestModel 上的错误;说“必须初始化非 Nullable 实例字段‘requestModel’。

然后 requestModel = new LoginRequestModel() 上的错误消息说 The Named Parameter 'email is required,但没有相应的参数。

并且 Last On OnSaved = 输入说“'String 类型的值?'不能分配给“字符串”类型的变量。”

非常感谢您给出的答案

【问题讨论】:

    标签: visual-studio flutter dart


    【解决方案1】:

    LoginRequestModel requestModel 上的错误;说“必须初始化非 Nullable 实例字段‘requestModel’。

    你需要改变:

    LoginRequestModel requestModel;
    

    由于您首先在initState 中设置值,因此不会立即为变量赋值,然后创建对象:

    late LoginRequestModel requestModel;
    

    然后 requestModel = new LoginRequestModel() 上的错误消息说 命名参数 'email 是必需的,但没有对应的 论据。

    我不知道LoginRequestModel 类的内容,但我猜它有一个命名参数email,需要在调用LoginRequestModel 构造函数时指定。

    最后 OnSaved = 输入说“'String 类型的值?'不能分配给“字符串”类型的变量。”

    同样,我不知道您的 LoginRequestModel 类,但我猜 email 字段不可为空。这是一个问题,因为onSave 需要一个带有签名的方法:

    void FormFieldSetter<T>(
        T? newValue
    ) 
    

    所以你的代码没有考虑到input 是一个可以为空的变量:

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

    由于您的一些问题与 Dart 空安全问题有关,我建议您阅读:https://dart.dev/null-safety

    【讨论】:

    • 所以我需要在这里显示我的 LoginRequestModel 代码?
    • @HandikaPramudyaPutra 是的,我可以在您的 LoginRequestModel 中看到不允许 emailpassword 具有值 null (因为它们都具有 String 类型而不是String?)。如果你不想要null,你需要处理onSaved中的input可以是null的情况(因为input的类型是String?)。你可以例如将行更改为:onSaved: (input) =&gt; requestModel.email = input ?? '',如果您想将email 设置为空字符串,以防inputnull。或者,您可以将email 更改为String?,或者在null 的情况下不要更改email
    【解决方案2】:

    一个接一个,

    第一个,你将LoginRequestModel requestModel定义为默认不可为空意味着这个变量被声明正常不能为空。 more detail 您可以将LoginRequestModel requestModel; 更改为LoginRequestModel requestModel= new LoginRequestModel();,而不是在initState 中给出值。好像

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

    或者使用late(很贵)

    第二个,我认为LoginRequestModel 会像这样LoginRequestModel({@required this.email})。您可以选择删除@required 或提供一个空值。

    最后一个,因为requestModel.passwordrequestModel.email是不可为空的,它应该像onSaved: (input) =&gt; requestModel.email = input!;

    【讨论】:

    • 有人说如果我删除那些我的代码无法运行,需要在 this.email 上加上 required
    • 也许你可以给它一个空值或者真正传递一个真实的数据。我不确定。这取决于您的 LoginRequestModel
    猜你喜欢
    • 2022-12-04
    • 1970-01-01
    • 2022-10-31
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多