0

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

How on all page use myUsername as global variable?

1
  • 1
    Check provider package for state management or create a singleton class ... Commented Aug 17, 2021 at 10:09

2 Answers 2

1

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")

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.