英文:
Dart / Flutter and REST client
问题
我不熟悉Dart的内存模型。在我的应用中,我创建一个客户端来与REST API通信,并将此客户端传递给多个小部件。这个客户端处理令牌(作为属性)以进行API身份验证。
@override
void initState() {
super.initState();
_widgetOptions = <Widget>[
MyAwesomeWidget(client: widget.client),
MyWidget(client: widget.client),
SettingsPage(client: widget.client)
];
}
SettingsPage
小部件包含一个注销按钮,将客户端持有的令牌置为空。此时,我期望客户端对所有引用它的小部件都不可用(不用担心,我有代码来处理所有小部件中的这种情况)。我对吗?或者客户端会以某种方式复制到其他小部件中?
英文:
I'm not proficient with Dart's memory model. In my app, I create a client to talk to a REST api, and I pass this client to several widgets. This client handles tokens (as attributes) to authenticate with the API.
@override
void initState() {
super.initState();
_widgetOptions = <Widget>[
MyAwesomeWidget(client: widget.client),
MyWidget(client: widget.client),
SettingsPage(client: widget.client)
];
}
The SettingsPage
widget contains a logout button that nullifies the tokens held by the client. At this point, I'm expecting the client to be unusable by all the widget with a reference to it (don't worry, I have code to handle this case in all the widgets). Am I right here? Or is the client somehow copied into the other widgets?
答案1
得分: 0
如果令牌数据成员在客户端内部定义,并且不被消费者小部件外部复制,那么它将按照您的期望行为。
- 如果您只在客户端端无效令牌(也许以后返回相同的令牌),请确保它被正确封装。
- 如果您在服务器端无效令牌,那么您的消费者小部件应该处理失败的 API 请求。
至于Dart内存模型:
"基本类型(如int、bool和num)按值传递。对象按引用传递。这与Java中传递参数的行为相同。" - Emily Fortuna
英文:
If the token data member is defined inside the client, and is not copied externally by the consumer widgets, then it will behave as you expect.
- If you're only invalidating the token client side (maybe to return the same token later), make sure it is properly encapsulated.
- If you're invalidating the token server-side, then your consumer widgets should handle failing API requests.
As for the Dart memory model:
"Primitives (like int, bool, and num) are passed by value. Objects are passed by reference. This is the same behavior as in Java for passing arguments." - Emily Fortuna
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论