Dart中的全局变量 [英] Global Variables in Dart

查看:3247
本文介绍了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-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
$ b

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;

您也可以

- 在全局库中创建单例a href =http://stackoverflow.com/questions/12649573>如何在Dart中构建Singleton?以获取更多详细信息)。

- 使用observable获取有关更改的通知(请参阅在Dart中实施观察者模式如何我可以在类中触发一种onChange事件更多细节)

You can also
- 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆