简体   繁体   English

dart class 构造函数中的可选 Arguments

[英]Optional Arguments in dart class constructor

why there is error while am trying to construct my constructor i want to have a named paramters but not required ones how i can fix this为什么在尝试构造我的构造函数时出现错误我想要一个命名参数但不是必需的我如何解决这个问题

class Task {
   int id;
   String title;
   String description;

  **Task({this.id , this.title , this.description}); // Giving me Errors here**

  Map<String , dynamic> toMap()
  {
    return {
      'id' : id,
      'title' : title,
      'description' : description,
    };
  }
  @override
  String toString() {
    return 'Task{id: $id, name: $title, age: $description}';
  }
}

If you don't want the arguments to be required , you have to allow them to be null by adding a question mark to their type, so Dart will know that they don't need to be initialized.如果您不希望required arguments ,则必须通过在其类型中添加问号来允许它们为null ,因此 Dart 将知道它们不需要初始化。 Like this:像这样:

   int? id;
   String? title;
   String? description;

Another solution is to give them a default value in the constructor, but be careful to assign them values that won't conflict with the rest of your code:另一种解决方案是在构造函数中给它们一个默认值,但要小心为它们分配的值不会与代码的 rest 冲突:

Task({this.id=-1, this.title='Title' , this.description = 'Description'});

Choose the approach that suits you best: you can also use a mix of the two solutions, like making some properties nullable and giving a default value to the others.选择最适合您的方法:您还可以混合使用这两种解决方案,例如使某些属性可为空并为其他属性提供默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM