Global Variables in Dart

T00rk picture T00rk · Mar 21, 2015 · Viewed 77.4k times · Source

I try to create a Dart single page 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.

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 ?

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.

Is it possible to do it ?

Answer

Günter Zöchbauer picture Günter Zöchbauer · Mar 21, 2015

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;

You can also