getToken
- Flutter course
- Advanced
- Lesson 27/69
- 4 min
Get the device token with getToken.
The getToken method
The getToken method returns a unique token that identifies the device. This token is sent to the server and used to route notifications to this device. The method is asynchronous, so you await it with await.
final token = await messaging.getToken();
print(token);APNS and FCM token
On iOS an APNS token is required; on Android the FCM token is used directly. The getToken method returns the appropriate token for the platform. On iOS a token cannot be obtained before notification permission is requested.
await messaging.requestPermission();
final token = await messaging.getToken();Practice Get the token and print it
Get the messaging instance, await the token with getToken and print it.
Starter code
class FirebaseMessaging {
static final FirebaseMessaging instance = FirebaseMessaging._();
FirebaseMessaging._();
Future<String?> getToken() async => 'token123';
}
void main() async {
// token al ve yazdır
}Sample solution
class FirebaseMessaging {
static final FirebaseMessaging instance = FirebaseMessaging._();
FirebaseMessaging._();
Future<String?> getToken() async => 'token123';
}
void main() async {
final token = await FirebaseMessaging.instance.getToken();
print(token);
}Expected output
token123
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the getToken method return?
- An int number
- Widget
- Stream<String>
- Future<String?> Correct answer
Explanation: getToken is an asynchronous method and returns Future<String?>; the token can be null.
2 Call getToken
final token = await FirebaseMessaging.instance.____;
final token = await FirebaseMessaging.instance.getToken();
Explanation: The getToken method is called with parentheses and awaited; without parentheses it returns a method reference.
3 getToken parts
| Term | Meaning |
|---|---|
getToken |
Returns the device token |
Future<String?> |
Return type |
token |
Device identifier |
APNS |
iOS notification service |