class Hotel {
static final Map<String, List<String>> mapInformation = {
'Americana Hotel': [
'4.3*',
'$4000 / Night',
],
};
String getPrice(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(1) ??
'It may need fixes';
}
String getRating(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(0) ??
'It may need fixes';
}
}
class Home {
static final Map<String, List<String>> mapInformation = {
'Beachside Resort': [
'2.2*',
'$2200 / Night',
],
};
String getPrice(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(1) ??
'It may need fixes';
}
String getRating(String favouriteElementsName) {
return mapInformation[favouriteElementsName]?.elementAt(0) ??
'It may need fixes';
}
}
class Favourite {
final LinkedHashMap<String, dynamic> favouriteElementsInLinkedHashMap =
LinkedHashMap();
void changePrice(String favouriteElementKey, Object obj) {
obj.mapInformation[favouriteElementKey]?[1] = '$5000 / Night';
var str1 = obj.getPrice(favouriteElementKey);
var str2 = obj.getRating(favouriteElementKey);
}
void main() {
var fav = Favourite();
favouriteElementsInLinkedHashMap['Americana Hotel'] = Hotel;
favouriteElementsInLinkedHashMap['Beachside Resort'] = Home;
for (var mapKey in favouriteElementsInLinkedHashMap.keys) {
fav.changePrice(
mapKey, favouriteElementsInLinkedHashMap[mapKey]);
}
}
}
There is method changePrice, it gives me an error when i use mapInformation, is there any way, how can i use mapInformation, getPrice, getRating in method changePrice. There are a lot of classes as Hotel and Home. So I can’t use if,else in method changePrice.
2
Answers
Make an abstract class that defines those methods:
Now both
Hotel
andHome
should extend that abstract class, and annotate the overriding methods with@override
:Change the type of the
obj
parameter:Please note that you can’t access
mapInformation
fromobj
, becausemapInformation
is a static field of the class. Preferably you should define another method inside the abstract class and implement it in the extending classes that modifiesmapInformation
.There are also other Dart class modifiers that might suit for your case, see Class modifiers.
You could use interface that in terms of dart is an abstract class e.g.
Then you could use it like this:
Finally, in the method changePrice you could use mapInformation:
More info about Class modifiers here