首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dart中的构造器零安全

Dart中的构造器零安全
EN

Stack Overflow用户
提问于 2022-06-22 13:29:56
回答 3查看 80关注 0票数 0

请告诉我。为什么默认情况下pr2为null而不是str1?

代码语言:javascript
复制
void main() {
  var house = Home(pr1: 4, pr3: 5);
  house.printDate();
}

class Home {
  int pr1=1;
  String? pr2 = 'str1';
  int pr3=3;
  Home({required this.pr1, this.pr2, required this.pr3});

  void printDate() {
    print('The pr1: $pr1');
    print('The pr2: $pr2');
    print('The pr3: $pr3');
  }
}

pr1: 4 pr2: null pr3: 5

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-06-22 14:03:09

因为默认情况下,可选参数是null,除非构造函数定义中另有规定。如果要声明另一个默认值,则需要使用以下语法:

代码语言:javascript
复制
void main() {
  var house = Home(pr1: 4, pr3: 5);
  house.printDate();
  // The pr1: 4
  // The pr2: str1
  // The pr3: 5
}

class Home {
  int pr1=1;
  String? pr2;
  int pr3=3;
  Home({required this.pr1, this.pr2 = 'str1', required this.pr3});

  void printDate() {
    print('The pr1: $pr1');
    print('The pr2: $pr2');
    print('The pr3: $pr3');
  }
}
票数 3
EN

Stack Overflow用户

发布于 2022-06-22 14:59:32

为了提高可读性,我重构了您的代码,并使用if-else语句删除了第一个解决方案。

代码语言:javascript
复制
class Home {
  //initialize the variables using the final keyword
  final int? pr1;
  final String? pr2;
  final int? pr3;
  
  //set the constructors
  Home({required this.pr1, this.pr2, required this.pr3});
  
void printDate(){
  //using the pr1 value
  print('The pr1: $pr1');
  //perfoming a runtime assertation for dev
  //assert(pr2 == null);//if the value for pr2 is null; it run smoothly
  //using if-else statement, I can tell wht is shows as outcome
  if (pr2 == null){
    print('The pr2: str1');
  }else{print('The pr2: $pr2');}//I would be rewriting this as a tenary operator


  //using the pr3 value
  print('The pr3: $pr3');
}
}
//the app starts ro run from here  
void main(){
  var house = Home(pr1:5,pr3:6,);
  house.printDate();
}

从上面可以看到,当pr2的条件为null时,它将显示文本'str1‘,如果它不是null,则显示pr2的值。希望这能帮上很多忙。

票数 -2
EN

Stack Overflow用户

发布于 2022-06-22 15:21:14

第二种方法是使用tenary运算符检查空值。

代码语言:javascript
复制
class Home {
  //initialize the variables using the final keyword
  final int? pr1;
  final String? pr2;
  final int? pr3;

  //set the constructors
  Home({required this.pr1, this.pr2, required this.pr3});

  void printDate() {
    //using the pr1 value
    print('The pr1: $pr1');
//pr2 check for null safety using tenary
    pr2 == null ? print('The Pr2: str1'):print('The pr2:$pr2');
    //using the pr3 value
    print('The pr3: $pr3');
  }
}

//the app starts ro run from here
void main() {
  var house = Home(
    pr1: 5,
    pr3: 6,
  );
  house.printDate();
}

十元是什么意思?简单地说,把它看作是一种逻辑条件,一种如果

代码语言:javascript
复制
 condition?expression1:expression2;

如果条件为真,则表达式1运行,如果条件为false,则表达式2运行。要回答您的问题,从第2.12段开始,它变成了空安全,对于构造函数的变量来说,这不是一个安全的实践。如有需要,我乐意作进一步解释。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72716451

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档