address_model.dart
class Address {
String placeFormattedAddress;
String placeName;
String placeId;
double latitude;
double longitude;
Address(this.latitude, this.longitude,
this.placeFormattedAddress,
this.placeId, this.placeName);
}
这是assistant_methods.dart
if (response != "failed") {
placeAddress = response["results"][0].
["formatted_address"];
Address userPickUpAdress = Address();
userPickUpAdress.longitude = position.longitude;
userPickUpAdress.latitude = position.latitude;
userPickUpAdress.placeName = placeAddress;
Provider.of<AppData>(context, listen: false)
.updatePickUpAdress(userPickUpAdress);
}
错误行在第4行的assitant_methods.dart上,也就是我调用Address()的时候,在下面的代码中,我已经初始化了
您声明的地址如下:
Address(
this.latitude,
this.longitude,
this.placeFormattedAddress,
this.placeId,
this.placeName,
);
这意味着在初始化地址时,您必须传递五个参数。为了解决这个问题,您必须做两件事。首先,使参数是可选的,这样您就不会HAVE将它们传递到构造函数中。
Address({
this.latitude,
this.longitude,
this.placeFormattedAddress,
this.placeId,
this.placeName,
});
注意所有可选参数周围的{}
。
这意味着您可以不向构造函数传递任何值。但也许更好的解决方案是首先简单地传递这些值。
需要解决的第二个问题是未初始化变量的值。如果你读到placeId,你认为会发生什么?你从来没有分配它。它应该抛出一个错误吗?它应该是一个空字符串吗?它应该为null吗?对每一个变量都要问自己这个问题。
如果变量应该有一个默认值(比如一个空字符串),你可以把它放在构造函数中:
MyClass({this.myValue: 'default value'});
如果变量在未传递的情况下引发错误,则可以像现有变量一样保留该变量,或者向构造函数添加所需的参数。
MyClass(this.myRequiredVariable, {required this.myOtherRequiredVariable});
最后,如果值应该为null。当您声明变量时。在其值后添加一个问号,表示其可以为空
class MyClass {
String? myNullableString;
}
最后,值得注意的是,这有一个副作用,即如果你想从构造函数初始化一个值,你必须传递它的名称:
MyClass({this.value});
// when initializing
// MyClass(10); // this won't work
MyClass(value: 10); // This will work
如果您不想这样做,请随意将构造函数上的{}
替换为[]
,这也将使required
关键字无法使用。
希望这足以解决问题,但如果我不清楚的内容,请随时询问
嗨,Iamshabell,欢迎来到SO!
您正试图在没有任何参数的情况下使用构造函数:
Address userPickUpAdress = Address();
但是在您的类上,构造函数参数是强制性的:
Address(this.latitude, this.longitude, this.placeFormattedAddress, this.placeId, this.placeName);
因此,您需要使它们成为可选的,或者使用所有参数调用构造函数。