Pointer
Pointer

Reputation: 2186

How set and use global variable in flutter app

On main.dart I get response from api username and set `String myUsername = 'stackoverflow';

How on all page use myUsername as global variable?

Upvotes: 0

Views: 2971

Answers (2)

t00n
t00n

Reputation: 415

You can create a Singleton like this:

class SingletonTest{
  String myUsername;

  SingletonTest._private();

  static SingletonTest _instance = SingletonTest._private();
  static SingletonTest get instance => _instance;
}

After that, you can access it from anywhere in your code using:

var singl = SingletonTest.instance;

For more examples refer to:

How to build a Singleton in dart

Or you can use Provider Pattern, more info about it here:

Provider Pattern

Upvotes: 1

Vaidehee Vala
Vaidehee Vala

Reputation: 392

the answer above is right , however if you don't want to make a singleton class, all you can do is, save it to shared preference, using the shared_preferences

myPreference.setString("userName", Your user name)

and get it using

myPreference.getString("userName")

Upvotes: 1

Related Questions