Flutter-Non-nullable instance field '{0}' must be initialized 错误

Flutter-Non-nullable instance field ‘{0}’ must be initialized error

我创建了一个单独的 class“DirectionDetails”,它是;

class DirectionDetails{

  int distanceValue;
  int durationValue;
  String distanceText;
  String durationText;
  String encodedPoints;

  DirectionDetails(this.distanceValue, this.durationValue, this.distanceText, this.durationText, this.encodedPoints);

}

当我尝试通过 DirectionDetails tripDirectionDetails; 在主 class 中初始化它时,它给出

Non-nullable instance field 'tripDirectionDetails' must be initialized

错误。但正如它所暗示的那样,当我添加“晚”修饰符时 - 它不会显示任何错误 但是当我 运行 应用程序 它给出了,

LateInitializationError: Field 'tripDirectionDetails' has not been initialized.

运行时间错误

我尝试了另一种方法,当我尝试使用

在主 class 中初始化 tripDirectionDetails
DirectionDetails tripDirectionDetails = new DirectionDetails();

并修改 DirectionDetails class

class DirectionDetails{

  int distanceValue;
  int durationValue;
  String distanceText;
  String durationText;
  String encodedPoints;

  DirectionDetails({this.distanceValue = 0, this.durationValue = 0, this.distanceText = "", this.durationText = "", this.encodedPoints = ""});
  
}

App 运行s 成功,它检索“DirectionDetails”中的所有值class 仅用于初始重启。

但是当我退出应用程序并返回时,出现以下错误。

LateInitializationError: Field 'tripDirectionDetails' has not been initialized.

非常感谢您的帮助。

谢谢

发生这种情况是因为您在初始化之前尝试使用 tripDirectionDetails。您应该仅将 late 用于非空变量,这些变量将在稍后尝试使用之前进行初始化:

tripDirectionDetails != null /// This will trigger an error

buildinitState:

中使用它之前,您应该对其进行初始化
@override
  void initState() {
    tripDirectionDetails = DirectionDetails();
    super.initState();
  }

但是由于tripDirectionDetails可以为空,所以最好这样声明:

DirectionDetails? tripDirectionDetails;

tripDirectionDetails != null /// Won't trigger an error