Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Firebase環境でWebPush
//こっちはFunctions側
import 'package:http/http.dart' as http;
import 'package:sprintf/sprintf.dart';
const String ENDPOINT = 'https://iid.googleapis.com/iid/v1/%s/rel/topics/%s';
Future<int> Subscribe(String serverKey, String token, String topic) async {
int status;
var url = sprintf(ENDPOINT, [token, topic]);
print(url);
var header = {
'Content-Type': 'application/json',
'Authorization': 'key=$serverKey'
};
await http.post(url, headers: header).then((response) {
status = response.statusCode;
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
return status;
}
//抜粋。
void ngOnInit() async{
registration = await sw.ready;
messaging = fb.messaging()
..usePublicVapidKey("")//自分の鍵を
..useServiceWorker(registration.jsObject);
messaging.onMessage.listen((payload) {
print(payload);
Notification(payload.notification.title,
body: payload.notification.body);
});
messaging.onTokenRefresh.listen((payload) {
print(payload);
});
bloc.result.listen((onData)=>(onData){
print("onData");
print(onData);
});
}
void requestNotificationPermission() async {
try {
await messaging.requestPermission();
final token = await messaging.getToken();
print(token);
} catch (e) {
print(e);
}
}
@JS()
library messaging_demo.service_worker;
import 'package:firebase/firebase.dart';
import 'package:js/js.dart';
import 'package:pwa/worker.dart';
import 'package:firebase/firebase.dart' as firebase;
import 'package:service_worker/worker.dart' as sw;
import 'package:Manma/pwa/offline_urls.g.dart' as offline;
void main() async{
Worker worker = new Worker();
importScripts("https://www.gstatic.com/firebasejs/5.7.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.7.1/firebase-messaging.js");
initializeApp(
apiKey: " ",
authDomain: "",
databaseURL: " ",
projectId: " ",
storageBucket: " ",
messagingSenderId: " "
);
final messaging = firebase.messaging();
messaging.onBackgroundMessage.listen((payload) {
final options = sw.ShowNotificationOptions(body: payload.notification.body);
sw.registration.showNotification(payload.notification.title, options);
});
worker.offlineUrls = offline.offlineUrls;
worker.run(version: offline.lastModified);
}
@JS('importScripts')
external void importScripts(String url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment