英文:
what is the use of using setters and getters in provider Class?
问题
以下是要翻译的内容:
It is a pretty basic question. I started off using the provider class without any getters and setters, but recently I see a lot of examples of this class using getters and setters. I remember using them in Java or something and have completely removed them as I didn't find any need. However, can someone explain if it is actually necessary? I have no code to post as it's a pretty generic question.
For the sake of an example: a typical provider class, do I need setters and getters for customMarkers
?
List<Marker> customMarkers = [];
void removeCustomMarker(String name) {
customMarkers.removeWhere(
(element) => element.key.toString().substring(3, 7) == name);
notifyListeners();
}
英文:
It is a pretty basic questions, i started off using the provider class without any getters and setters, but recently i see a lot of examples of this class using getters and setters, i remember using them in java or sth and have completely removed them as i didn't find any need?
How ever can some one explain if it is actually necessary? I have no code to post as it pretty generic question.
for the sake of an example: a typical provider class, do i need to setters and getters fro customMarkers
?
List<Marker> customMarker = [];
void removeCustomMarker(String name) {
customMarker.removeWhere(
(element) => element.key.toString().substring(3, 7) == name);
notifyListeners();
}
答案1
得分: 2
你想要使用getter和setter,因为它允许您分离每个实例所需的内容,例如,如果您只获取值,就不应通知监听器。
class AppProvider {
List<Marker> _customMarkers = [];
get customMarkers {
return _customMarkers;
}
set customMarkers(String name) {
_customMarkers.removeWhere((element) => element.key.toString().substring(3, 7) == name);
notifyListeners();
}
}
class ExampleWidget extends StatelessWidget {
appProvider = new AppProvider();
// widget将由监听它的提供者包含
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
appProvider.customMarkers;
),
TextButton(
onTap: () => {
appProvider.customMarkers = 'new Value';
},
)
],
);
}
}
英文:
You want to use getter/setters because it lets you split what is needed for each instance, for example you shouldn't notify listeners if you are only getting the value.
class AppProvider {
List<Marker> _customMarkers = [];
get customMarkers {
return _customMarkers;
}
set customMarkers(String name) {
_customMarker.removeWhere((element) => element.key.toString().substring(3, 7) == name);
notifyListeners();
return customMarkers;
}
}
class ExampleWidget extends StatelessWidget {
appProvider = new AppProvider();
// widget would be contained by your provider that would be listening
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
appProvider.customMarkers;
),
TextButton(
onTap: () => {
appProvider.customMarkers = 'new Value';
},
)
],
);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论