Alif Al-Gibran
Alif Al-Gibran

Reputation: 1246

How to set token as a global variable in flutter? so i can access the token wherever i want

I build an app using Firebase Authentication, after login, I have to save the token as a global variable so I can use that token wherever I want. I have tried to pass it as global variable in constant but I got stuck when because when I re-run the app, the token is erased.

thank you.

Upvotes: 0

Views: 2061

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80934

You can save the token inside the package shared_preferences:

Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data. Data is persisted to disk asynchronously

To save data:

addStringToSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('token', "token_value");
}

To read data:

getStringValuesSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  //Return String
  String token = prefs.getString('token');
  return token;
}

https://pub.dev/packages/shared_preferences

Upvotes: 1

Related Questions