Non-nullable instance field ‘height‘ must be initialized.

记录:
今天用dartpad练习的时候,莫名报出这个错误:
Non-nullable instance field ‘height’ must be initialized.
突然想起来之前一直用的是老版本的dart,而dartpad的dart版本比较新,断定这个问题应该是和‘空安全’相关,随后对代码进行了调整

调整前:

class Rect{
    
    

  int height;
  int width;
 
  getArea(){
    
    
    return this.height*this.width;
  } 
}


class Rect{
    
    
  num height;
  num width; 
  
  Rect(this.height,this.width);
  area(){
    
    
    return this.height*this.width;
  }
}

void main(){
    
    
  Rect r=new Rect(10,4);
  print("面积:${r.area()}");   
}





class Rect{
    
    
  num height;
  num width;   
  Rect(this.height,this.width);
  get area{
    
    
    return this.height*this.width;
  }
}

void main(){
    
    
  Rect r=new Rect(10,2);
  print("面积:${r.area}");  
}

调整后:

class Rect{
    
    
  late num height;
  late num width;   
  Rect(this.height,this.width);
  get area{
    
    
    return this.height*this.width;
  }
  set areaHeight(value){
    
    
    this.height=value;
  }
}

void main(){
    
    
  Rect r=new Rect(10,4);
  // print("面积:${r.area()}");   
  r.areaHeight=6;

  print(r.area);

}

对于不可为空的变量,在定义之前加上‘late’关键字能解决这个问题

之后要去学习空安全相关知识

猜你喜欢

转载自blog.csdn.net/weixin_46136019/article/details/128880165