Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mess compat #1785

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 128 additions & 54 deletions packages/firebase_messaging/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,64 @@
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:http/http.dart' as http;

final Map<String, Item> _items = <String, Item>{};
Item _itemForMessage(Map<String, dynamic> message) {
final dynamic data = message['data'] ?? message;
final String itemId = data['id'];
final Item item = _items.putIfAbsent(itemId, () => Item(itemId: itemId))
..status = data['status'];
return item;
}
final Map<String, Notification> _notifications = <String, Notification>{};

class Item {
Item({this.itemId});
final String itemId;
class Notification {
Notification.fromJson(Map<String, dynamic> message)
: title = message['notification']['title'],
body = message['notification']['body'],
id = message['id'];

StreamController<Item> _controller = StreamController<Item>.broadcast();
Stream<Item> get onChanged => _controller.stream;
final String id;
final String title;
final String body;

String _status;
String get status => _status;
set status(String value) {
_status = value;
_controller.add(this);
}
StreamController<Notification> _controller =
StreamController<Notification>.broadcast();
Stream<Notification> get onChanged => _controller.stream;

static final Map<String, Route<void>> routes = <String, Route<void>>{};

Route<void> get route {
final String routeName = '/detail/$itemId';
final String routeName = '/detail/$id';
return routes.putIfAbsent(
routeName,
() => MaterialPageRoute<void>(
settings: RouteSettings(name: routeName),
builder: (BuildContext context) => DetailPage(itemId),
builder: (BuildContext context) => DetailPage(this),
),
);
}
}

class DetailPage extends StatefulWidget {
DetailPage(this.itemId);
final String itemId;
DetailPage(this.notification);

final Notification notification;

@override
_DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
Item _item;
StreamSubscription<Item> _subscription;
StreamSubscription<Notification> _subscription;

@override
void initState() {
super.initState();
_item = _items[widget.itemId];
_subscription = _item.onChanged.listen((Item item) {
_subscription =
widget.notification.onChanged.listen((Notification notification) {
if (!mounted) {
_subscription.cancel();
} else {
setState(() {
_item = item;
});
setState(() {});
}
});
}
Expand All @@ -73,10 +69,10 @@ class _DetailPageState extends State<DetailPage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Item ${_item.itemId}"),
title: Text('Title: ${widget.notification.title}'),
),
body: Material(
child: Center(child: Text("Item status: ${_item.status}")),
child: Center(child: Text('Body: ${widget.notification.body}')),
),
);
}
Expand All @@ -90,14 +86,17 @@ class PushMessagingExample extends StatefulWidget {
class _PushMessagingExampleState extends State<PushMessagingExample> {
String _homeScreenText = "Waiting for token...";
bool _topicButtonsDisabled = false;

final String serverToken = '<Server-Token>';
final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
final TextEditingController _topicController =
TextEditingController(text: 'topic');
final TextEditingController _topicController = TextEditingController(
text: 'topic',
);

Widget _buildDialog(BuildContext context, Item item) {
Widget _buildDialog(BuildContext context, Notification notification) {
return AlertDialog(
content: Text("Item ${item.itemId} has been updated"),
content: Text("Notification ${notification.id} has been updated"),
actions: <Widget>[
FlatButton(
child: const Text('CLOSE'),
Expand All @@ -118,26 +117,103 @@ class _PushMessagingExampleState extends State<PushMessagingExample> {
void _showItemDialog(Map<String, dynamic> message) {
showDialog<bool>(
context: context,
builder: (_) => _buildDialog(context, _itemForMessage(message)),
builder: (_) {
Notification notification = Notification.fromJson(message);
notification = _notifications.putIfAbsent(
notification.id,
() => notification,
);
return _buildDialog(context, notification);
},
).then((bool shouldNavigate) {
if (shouldNavigate == true) {
_navigateToItemDetail(message);
}
});
}

Future<void> _sendMessage() async {
await _firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(
sound: true, badge: true, alert: true, provisional: false),
);

await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'this is a body',
'title': 'this is a title'
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '2',
'status': 'done'
},
'to': await _firebaseMessaging.getToken(),
},
),
);

final NotificationDetails details = NotificationDetails(
AndroidNotificationDetails(
'your other channel id',
'your other channel name',
'your other channel description',
importance: Importance.Max,
priority: Priority.High,
ticker: 'ticker',
),
IOSNotificationDetails(),
);
await _notificationsPlugin.show(0, 'plain title', 'plain body', details,
payload: 'plain payload');
}

void _navigateToItemDetail(Map<String, dynamic> message) {
final Item item = _itemForMessage(message);
final Notification notification = Notification.fromJson(message);
// Clear away dialogs
Navigator.popUntil(context, (Route<dynamic> route) => route is PageRoute);
if (!item.route.isCurrent) {
Navigator.push(context, item.route);
if (!notification.route.isCurrent) {
Navigator.push(context, notification.route);
}
}

@override
void initState() {
super.initState();
_setupFirebaseMessaging();
_setupLocalNotifications();
}

void _setupLocalNotifications() {
final InitializationSettings settings = InitializationSettings(
AndroidInitializationSettings('app_icon'),
IOSInitializationSettings(
onDidReceiveLocalNotification: (
int id,
String title,
String body,
String payload,
) {
print('onDidReceiveLocalNotification: $id $title $body $payload');
return Future<void>.value();
},
),
);
_notificationsPlugin.initialize(settings, onSelectNotification: (_) {
print('onSelectNotification: $_');
return Future<void>.value();
});
}

void _setupFirebaseMessaging() {
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
Expand All @@ -153,8 +229,13 @@ class _PushMessagingExampleState extends State<PushMessagingExample> {
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(
sound: true, badge: true, alert: true, provisional: true));
const IosNotificationSettings(
sound: true,
badge: true,
alert: true,
provisional: true,
),
);
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
Expand All @@ -174,23 +255,16 @@ class _PushMessagingExampleState extends State<PushMessagingExample> {
appBar: AppBar(
title: const Text('Push Messaging Demo'),
),
// For testing -- simulate a message being received
floatingActionButton: FloatingActionButton(
onPressed: () => _showItemDialog(<String, dynamic>{
"data": <String, String>{
"id": "2",
"status": "out of stock",
},
}),
tooltip: 'Simulate Message',
child: const Icon(Icons.message),
),
body: Material(
child: Column(
children: <Widget>[
Center(
child: Text(_homeScreenText),
),
RaisedButton(
child: Text('Send Message'),
onPressed: _sendMessage,
),
Row(children: <Widget>[
Expanded(
child: TextField(
Expand Down
2 changes: 2 additions & 0 deletions packages/firebase_messaging/example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ name: firebase_messaging_example
description: Demonstrates how to use the firebase_messaging plugin.

dependencies:
http: 0.12.0+4
firebase_analytics: any
flutter:
sdk: flutter
firebase_messaging:
path: ../
firebase_core: ^0.4.0
flutter_local_notifications: 0.9.1+2

dev_dependencies:
flutter_test:
Expand Down