Reputation: 15
I have already generated a Firebase token inside my app and I need to use it elsewhere in my code but all of the tutorials I have seen don't use it outside the
FirebaseMessaging.getToken.then((token){
print(token);
})
How can I use this variable elsewhere in my code?
Thanks in advance.
Upvotes: 0
Views: 446
Reputation: 1442
You have two options, First is to save it in SharedPrefs, if you want to store it and use it even after relaunching the application.
FirebaseMessaging.getToken.then((token){
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("Token",token);
})
and retrieve it anywhere in the app with
prefs.getString("Token");
You can also create a static variable in any class and use it but it will be available for only single launch.
class TokenClass {
static String token = "temp";
}
set and get it using TokenClass.token
Upvotes: 2
Reputation: 3998
You can save in sharedPrefs
or you can define global variable in your app.
globals.dart:
library myGlobals.globals;
String token;
and set global variables:
import 'package:PROJECT_NAME/globals.dart' as globals;
FirebaseMessaging.getToken.then((token){
globals.token = token;
})
and use:
import 'package:PROJECT_NAME/globals.dart' as globals;
print(globals.token)
Upvotes: 0