我正在尝试从 FirebaseMessaging 调用函数 requestPermission()。由于某种原因,这不会返回任何内容并且函数执行正在停止。
我正在 Windows 11 机器上的 VSCode 上进行编程,在 Web(Edge)上运行。我也在安卓手机上尝试过,但没有成功。
代码在这里:
void initPushNotification() async {
print("in async");
String? fcmToken;
try {
final fcm = FirebaseMessaging.instance;
print("requestperm");
final response = await fcm.requestPermission();
print(response.authorizationStatus.name);
print("got perm");
if (kIsWeb) {
print("is web");
fcmToken = await fcm.getToken(
vapidKey:
"A VAPID KEY HERE");
print("got token");
} else {
fcmToken = await fcm.getToken();
}
print(
fcmToken);
} catch (err) {
print(err);
}
print("end async");
}
@override
void initState() {
super.initState();
print("initstate");
try {
initPushNotification();
} catch (err) {
print("catch");
print(err);
}
print("finish initstate");
}
控制台输出:
initstate
in async
finish initstate
requestperm
pubspec 中的一些信息:
environment:
sdk: ^3.5.3
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
firebase_core: ^3.6.0
firebase_auth: ^5.3.1
firebase_storage: ^12.3.4
image_picker: ^1.1.2
cloud_firestore: ^5.4.4
firebase_messaging: ^15.1.4
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^4.0.0
flutter:
uses-material-design: true
我在控制台上没有任何类型的错误,即使在 Web 控制台上也是如此。
我期望函数 requestPermission() 实际请求权限...
我在网上搜索了一些解决方案,并遵循了firebase文档:https://firebase.flutter.dev/docs/messaging/overview和https://firebase.google.com/docs/cloud-messaging/颤振/接收?hl=fr.
也尝试过这个,即使它对我来说有点可疑: 将内容添加到 web 文件夹下的 index.html 中:
// IG the version here arent correct but i would expect a different kind of error if it was this
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
<script>
const firebaseConfig = {
apiKey: '...',
appId: '...',
messagingSenderId: '...',
projectId: '...',
authDomain: '...',
storageBucket: '...',
};
firebase.initializeApp(firebaseConfig);
</script>
<script src="main.dart.js" type="application/javascript"></script>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');
/*Update with yours config*/
const firebaseConfig = {
apiKey: '...',
appId: '...',
messagingSenderId: '...',
projectId: '...',
authDomain: '...',
storageBucket: '...',
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
/*messaging.onMessage((payload) => {
console.log('Message received. ', payload);*/
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
我错过了什么?
按照此逐步过程
第 1 步:尝试在 Chrome 而非 Edge 浏览器上启动 : -> 如果工作就不需要改变
第 2 步:如果在任何浏览器上得到相同的结果
就像应用程序未启动或启动但浏览器中没有任何视图(如白屏)并且没有收到任何错误一样。
在项目的 web 目录中的 index.html 文件中进行以下更改
检查以下函数必须是索引文件中的最后一个选项卡
<script>
window.addEventListener('load', function (ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function (engineInitializer) {
engineInitializer.initializeEngine().then(function (appRunner) {
appRunner.runApp();
});
}
});
});
</script>
<script src="main.dart.js" type="application/javascript"></script>
为了更多参考,我为您提供了我个人 flutter 项目(techcureindia.web.app)的整个index.html 文件
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<!-- Description -->
<meta name="description"
content="We are experts in workstatuions and gaming pc's | AI & deep learning pc | Architechture & Engineering pc | visual designer & video editor pc | trading pc | Audio production pc | Gaming pc | amd series | custom liquid cooling setup | Cryptocurrency mining rigs | All IT peripherals & much more.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- Change TITLE -->
<meta name="apple-mobile-web-app-title" content="Tech Cure India">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<!-- <link rel="icon" type="image/png" href="favicon.png" /> -->
<!-- Use .ico favicon -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- Change TITLE -->
<title>Tech Cure India</title>
<link rel="manifest" href="manifest.json">
<script>
// The value below is injected by flutter build, do not touch.
const serviceWorkerVersion = "2091515534";
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
<!-- This is for js in flutterWeb-->
<script src="appscript.js" defer></script>
<!-- This is for load our css file-->
<link rel="stylesheet" type="text/css" href="styles.css">
<!-- Toastify CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<!-- PDF View -->
<script>
var dartPdfJsVersion = "3.2.146";
</script>
</head>
<body>
<!-- Loading Indicator Below-->
<div class="loading">
<div class="loader"></div>
</div>
<!-- Loading Indicator Above-->
<!-- <script src="main.dart.js" type="application/javascript"></script> -->
<!-- Move above line bottom most-->
<!-- Firebase SetUp script type = 'module'-->
<!-- <script type="module">
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: "AIzaSyBenD4UHfJiCcodpSzYKFe4buxRg_ZfZic",
authDomain: "techcureindia.firebaseapp.com",
projectId: "techcureindia",
storageBucket: "techcureindia.appspot.com",
messagingSenderId: "1016267859555",
appId: "1:1016267859555:web:45e1e213f671b886323a56",
measurementId: "G-VNSZL96YJM"
};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script> -->
<!-- Firebase INIT way 2.0 -->
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-analytics.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=yourKey"></script>
<script>
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyBenD4UHfJiCcodpSzYKFe4buxRg_ZfZic",
authDomain: "techcureindia.firebaseapp.com",
projectId: "techcureindia",
storageBucket: "techcureindia.appspot.com",
messagingSenderId: "1016267859555",
appId: "1:1016267859555:web:45e1e213f671b886323a56",
measurementId: "G-VNSZL96YJM"
};
/// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<!-- Firebase INIT way 2.0 -->
<!-- syncfusion-PDF -->
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
<script type="text/javascript">
pdfjsLib.GlobalWorkerOptions.workerSrc = "//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js";
</script>
<script>
window.addEventListener('load', function (ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function (engineInitializer) {
engineInitializer.initializeEngine().then(function (appRunner) {
appRunner.runApp();
});
}
});
});
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
如果仍然出现错误,请提供项目的整个index.html文件
希望这对你有帮助