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 ...
    – Omar Fayad
    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")

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.