我有一个应用程序应该将 Firebase token 从我的 Flutter 应用程序发送到 ASP.Net 应用程序服务器。应用服务器上的端点工作 - 从 Flutter 应用到应用服务器的请求不工作。
它不起作用的原因是因为当我尝试发送 token 时, token 似乎还没有到达 - 它是 Future 类型。当它最终到达时,我如何将该标记转换为字符串?
我尝试过在 fcmStream.Listen 函数中将 token 直接转换为字符串,我还尝试使用 _firebaseMessaging.getToken 将其转换为字符串。它们都不起作用
FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();
@override
void initState() {
// TODO: implement initState
super.initState();
location.onLocationChanged().listen((value) {
if (this.mounted) {
setState(() {
currentLocation = value;
});
}
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print('on message $message');
},
onResume: (Map<String, dynamic> message) {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) {
print('on launch $message');
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
String clientToken = _firebaseMessaging.getToken().then((token) {
print("Token Init: " + token.toString());
}
).toString();
BackendService.postToken(clientToken.toString(), "email@gmail.com");
@override
Stream<String> fcmStream = _firebaseMessaging.onTokenRefresh;
fcmStream.listen((token) {
/*print("Token On Refresh: " + token);
BackendService.postToken(token.toString(), "email@gmail.com");*/
}
);
fcmStream.toString();
class BackendService {
static Future<String> postToken(String token, String hostEmail) async {
final responseBody = (await http.get(
'realurlomitted/.../Meets/RegisterDevice?token=$token&hostEmail=$hostEmail')).body;
print(" Response: " + responseBody.toString());
return responseBody.toString();
}
}
每当打印 token.toString 时,它都会很好地打印 token - 我可以看到。似乎每当它尝试使用 http 发布帖子时,无论 getToken 是什么, token 都没有到达。
如果我可以通过等待它或其他东西将 Future 变成一个字符串,它会解决我的问题,这样 $token 参数就是作为字符串的 token 。
更具体地说,我的请求 URL 应该如下所示:
https://-----/Meets/RegisterDevice?token=c6V49umapn0:Jdsf90832094890s324&hostEmail=email@gmail.com
但它看起来像:
https://-----/Meets/RegisterDevice?token=instance of Future<Dynamic>&hostEmail=email@gmail.com
在 Flutter 调试器中
最佳答案
正如您所说,等待 future 将解决您的问题。您可以编写一个 async
函数并将代码放入您的 initState
中并使用 await
,或者您可以这样做:
_firebaseMessaging.getToken().then((token) {
final tokenStr = token.toString();
// do whatever you want with the token here
}
);
关于firebase - 使用 Flutter 将 Firebase token 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57188952/