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() 的時候,在下面的代碼中我已經初始化
uj5u.com熱心網友回復:
您宣告的地址如下:
Address(
this.latitude,
this.longitude,
this.placeFormattedAddress,
this.placeId,
this.placeName,
);
這意味著,在初始化時的地址,你HAVE傳遞五個引數,為了解決這個問題,你必須做兩件事情。首先,使引數可選,這樣您就不必將它們傳遞給建構式。
Address({
this.latitude,
this.longitude,
this.placeFormattedAddress,
this.placeId,
this.placeName,
});
注意{}所有可選引數的周圍。
這意味著您可以不向建構式傳遞任何值。但也許更好的解決方案是首先簡單地傳遞值。
您需要解決的第二個問題是未初始化變數的值。如果您閱讀 placeId,您認為會發生什么?你永遠不會分配它。它是否應該拋出錯誤(正如它所做的那樣)?它應該是一個空字串嗎?它應該為空嗎?對每一個變數問自己這個問題。
如果變數應該有一個默認值(比如一個空字串),你可以把它放在建構式中:
MyClass({this.myValue: 'default value'});
如果變數在您不傳遞的情況下應該拋出錯誤,您可以像擁有它一樣保留該變數,或者向建構式添加一個必需的引數。
MyClass(this.myRequiredVariable, {required this.myOtherRequiredVariable});
最后,如果值應該為空。當你宣告變數時。在其值后添加一個問號表示它可以為空
class MyClass {
String? myNullableString;
}
最后,值得注意的是,這有一個副作用,如果你想從建構式初始化一個值,你必須傳遞它的名字:
MyClass({this.value});
// when initializing
// MyClass(10); // this won't work
MyClass(value: 10); // This will work
如果您不希望那樣,請隨意替換建構式上的{}with [],這也將使required關鍵字無法使用。
希望這足以解決問題,但請隨時問我是否有不清楚的地方
uj5u.com熱心網友回復:
嗨 Iamshabell,歡迎來到 SO!
您正在嘗試在這一行不帶任何引數的情況下使用建構式:
Address userPickUpAdress = Address();
但是在您的類中,建構式引數是強制性的:
Address(this.latitude, this.longitude, this.placeFormattedAddress, this.placeId, this.placeName);
因此,您需要將它們設為可選項或使用所有引數呼叫建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338155.html
