Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variables in Dart

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 ?

like image 744
T00rk Avatar asked Mar 21 '15 12:03

T00rk


People also ask

How do you declare a global variable in Dart?

Just create a library file and create fields for globals you need there. Import this library everywhere you need access to these fields. create a singleton in the globals library (see How do you build a Singleton in Dart? for more details).

What do you mean by global variable?

In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.

How do I access a variable from another Dart file?

You need to import the file with the variable dateTime. Then you have 2 ways: make the variable static: static var dateTime. for this way you don't need todo know anything.


2 Answers

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

  • 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)
like image 123
Günter Zöchbauer Avatar answered Sep 20 '22 04:09

Günter Zöchbauer


You can create a class

myColors.dart

class AppColors {    static var primary = Colors.blue; } 

And importing your class

import 'package:myapp/.../myColors.dart'; 

And access with AppColors.primary

like image 28
Álvaro Agüero Avatar answered Sep 21 '22 04:09

Álvaro Agüero