Dart 中的全局变量 [英] Global Variables in Dart
问题描述
我尝试创建一个 Dart 单页应用程序.
I try to create a Dart single page application.
我创建了第一个包含整个应用程序的自定义元素 (custom-application
).它有一个用于渲染视图的容器.以及包含用户信息并在用户登录时更新的侧边导航.
I have created a first custom element (custom-application
) which contains the whole application.
It has a container in it which is used to render views. And a side nav which will contain user informations and be updated when the user is log in.
我想在视图之间共享信息.如何在 custom-application
中定义全局变量并能够与其他视图共享?
I want to share informations between views.
How can I define a global variable in custom-application
and be able to share it with the other views ?
例如,当您启动应用程序时,您未经过身份验证.当您调用/login (login-view
) 时,您将获得一个登录表单.我希望,当您登录应用程序时,custom-application
元素存储由嵌套视图 login-view
加载的用户信息并更新侧导航.
For example, when you start the app, you are not authenticated. When you call /login (login-view
) you'll have a login form. I want, when you log in the application, the custom-application
element stores the user informations loaded by the nested view login-view
and update the side nav.
可以吗?
推荐答案
只需创建一个库文件并为您需要的全局变量创建字段即可.在需要访问这些字段的任何位置导入此库.
Just create a library file and create fields for globals you need there. Import this library everywhere you need access to these fields.
app.dart
import 'globals.dart' as globals;
main() {
globals.isLoggedIn = true;
}
component1.dart
import 'globals.dart' as globals;
class MyComponent {
view() {
if(globals.isLoggedIn) {
doSomething();
else {
doSomethingElse();
}
}
}
globals.dart
library my_prj.globals;
bool isLoggedIn = false;
你也可以
- 在 globals 库中创建一个单例(请参阅如何在 Dart 中构建单例?了解更多详情).
- 使用 observable 获取有关更改的通知(请参阅在 Dart 中实现观察者模式、如何在类中触发一种 onChange 事件 了解更多详情)
- create a singleton in the globals library (see How do you build a Singleton in Dart? for more details).
- use observable to get notified about changes (see Implement an Observer pattern in Dart, How can i trigger a kind of onChange event in a class for more details)
这篇关于Dart 中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!