I'm trying to get notification action button data. That is when the user fill the input action, I get the data he entered.
Just like this.
I am using the awesome_notifcations flutter package.
This is my function to that creates new notification with input action for comment
Future<void> create({
required String key,
required String title,
required String body,
required String bigPicture,
}) async {
await _notiff.createNotification(
content: NotificationContent(
id: DateTime.now().millisecondsSinceEpoch.remainder(10),
channelKey: key,
title: title,
body: body,
bigPicture: bigPicture,
notificationLayout: NotificationLayout.BigPicture,
),
actionButtons: [
NotificationActionButton(
buttonType: ActionButtonType.InputField,
enabled: true,
label: "Comment",
key: "COMMENT_BUTTON_KEY")
]);
}
Here I just want to get the user's comment.
How to do so ?
Do you need create listener to get new notifications like this:
AwesomeNotifications().actionStream.listen(
(ReceivedNotification receivedNotification){
Navigator.of(context).pushNamed(
'/NotificationPage',
arguments: {
// your page params. I recommend you to pass the
// entire *receivedNotification* object
id: receivedNotification.id
}
);
}
);
PD: Do you need replace with your data, this information is in docs (5. How to show Local Notifications)
Related
I am having an issue where the local notification is not displaying in android though it is displaying in IOS. I have created permissions and battery optimization check to see if that is the problem. The notification does make a sound and appear shows a little square in the upper left that if I click and drag does show the local notification. I am using an emulator right now and I have tried it on a real device.
This is the way I am calling the notification.
<Button
title="Trigger Push Notification"
size="large"
onPress={() => onDisplayNotification('default', 'Default Channel', 'Spotback
Android', 'Local push notification')}
/>
This is is the Notifee component.
import notifee, { AndroidStyle, AuthorizationStatus, Notification } from '#notifee/react-native';
import { Alert } from 'react-native';
export const onDisplayNotification = async (id, name, title, body, smallIcon?) => {
// Request permissions (required for iOS)
await notifee.requestPermission();
const settings = await notifee.getNotificationSettings();
const batteryOptimizationEnabled = await notifee.isBatteryOptimizationEnabled();
if (batteryOptimizationEnabled) {
// 2. ask your users to disable the feature
Alert.alert(
'Restrictions Detected',
'To ensure notifications are delivered, please disable battery optimization for the app.',
[
// 3. launch intent to navigate the user to the appropriate screen
{
text: 'OK, open settings',
onPress: async () => await notifee.openBatteryOptimizationSettings(),
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
],
{ cancelable: false }
);
}
if (settings.authorizationStatus == AuthorizationStatus.AUTHORIZED) {
console.log('Notification permissions has been authorized');
} else if (settings.authorizationStatus == AuthorizationStatus.DENIED) {
console.log('Notification permissions has been denied');
}
// }
// Create a channel (required for Android)
const channelId = await notifee.createChannel({
id,
name,
});
await notifee.displayNotification({
title,
body,
android: {
channelId,
smallIcon,
pressAction: {
id,
},
},
});
};
Please change your channel id (default) and channel name (Default Channel) to something else like:
id: custom_channel
name: custom_channel
I'm new to flutter. I am trying to make an app for myself which can do some calculations for me.
The Situation: When I start the app it starts with the loading screen. While loading it make an API call to get some data which I
will need in the future. And send it to the pages where I need it. This is working fine.
The problem: I have multiple pages in the app. When I return from any other page to the main page the data got vanished. So I
have to make another API call to get the data back. And I don't want
this to happen
What I want: I want that when the data is received it should be stored somewhere locally so that I can use it wherever I want, without making another API call or without an internet connection.
Check the video demo here to understand better
What I am doing:
Loading screen:
class Loading extends StatefulWidget {
#override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupPair() async
{
CurrInfo instance =
CurrInfo(url: 'EUR/USD', flagA: 'eur.png', flagB: 'usd.png');
await instance.getInfo();
if (instance.price != "not connected")
{
Navigator.pushReplacementNamed(context, '/home', arguments: {
'url': instance.url,
'flagA': instance.flagA,
'flagB': instance.flagB,
'price': instance.price,
});
} // I don't want to send this instance, instead I want to store the Received
data locally and access that data from anywhere inside the app
Video else if (instance.price == "not connected") {
Navigator.pushReplacementNamed(context, '/not connected');
}
}
Getting data by making api call:
class CurrInfo {
String url;
String flagA;
String flagB;
String price;
String furl;
Map data;
List info;
CurrInfo({this.url, this.flagA, this.flagB});
Future<void> getInfo() async {
try {
print((url));
furl =
"https://fcsapi.com/api-v2/forex/latest?
symbol=$url&access_key=t58zo1uMFJZlNJxSrSmZv2qIUlSkCk9RAfCLkwnMwt1q1FFS";
Response response = await http
.get(Uri.encodeFull(furl), headers: {"Accept": "application/json"});
data = jsonDecode(response.body);
print(data);
info = data['response'];
print(info);
price = info[0]['price']; // I want to save this price data locally while loading so that I
don't have to make another API call to get it back and it should be
updated when I refresh the page
print("string price : $price");
} catch (e) {
price = "not connected";
print('error is : $e & $price');
}}}
How i'm using this data where i need :
Map data = {};
String ofData;
Expanded(flex: 1,
child: Text( ${data['url']}',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),
textAlign: TextAlign.start,
),
),
Expanded( flex: 1,
child: Text('${data['price']}',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.end,
),
),
Check out full code here to understand better
you can use this package shared_preferences: ^0.5.12+2 to store data locally on phone
I have a cloud function which executes this code to send the notification to the user, I am getting notification correctly but I want to navigate to a particular screen for that I have to add click action something like this.
clickAction: FLUTTER_NOTIFICATION_CLICK
I have tried to put this property in different lines of code but nothing seem to work, can someone please tell where should I put it exactly?
This is my index.js file!
const message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
}
console.log('Sending message');
const response = await admin.messaging().send(message);
console.log(response);
You can add clickAction: 'FLUTTER_NOTIFICATION_CLICK' in the following way
message = {
token: data['guestFcmToken'],
notification: {
title: `New message from ${data['hostName']}.`,
body: data['type'] === 'image' ? 'Photo' : data['lastMessage'],
},
data: {
showForegroundNotification: 'false',
screen: 'chat'
},
android: {
notification: {
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
},
}
};
I have create a notification like this:
const notification = new firebase.notifications.Notification()
.setNotificationId('1')
.setTitle('Reminder')
.setBody('Looooooooooooooooooooooonggggggg messageeeeeeeeeeeeeeeeeeeeee longggggggggggggg messsssssagggeeeeeeeeee')
.setData({
key: true,
data: {},
})
.android.setChannelId('test-channel')
.android.setAutoCancel(true)
.android.setPriority(firebase.notifications.Android.Priority.Max);
I want to show all the body message on notification. But it only show one line message.
There is a bigText prop in android object. You can see the documentation here https://rnfirebase.io/docs/v5.x.x/notifications/reference/AndroidNotification#setBigText but to summerize it something like this shoudlwork
const notification = new firebase.notifications.Notification()
.setNotificationId('1')
.setTitle('Reminder')
.setBody('Looooooooooooooooooooooonggggggg messageeeeeeeeeeeeeeeeeeeeee longggggggggggggg messsssssagggeeeeeeeeee')
.setData({
key: true,
data: {},
})
.android.setChannelId('test-channel')
.android.setAutoCancel(true)
.android.setBigText('Looooooooooooooooooooooonggggggg messageeeeeeeeeeeeeeeeeeeeee longggggggggggggg messsssssagggeeeeeeeeee')
.android.setPriority(firebase.notifications.Android.Priority.Max);
I'm working with Firebase notifications using node.js.
After compile, when I'm sending request to other user of app (request makes notification), firebase log shows error:
TypeError: Cannot read property 'receiver_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:12:36)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Index.js code:
'use strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite(event =>
{
const receiver_id = event.params.receiver_id;
const notification_id = event.params.notification_id;
console.log('We have a notification to send to :', receiver_id);
if(!event.data.val())
{
return console.log('A notification has been deleted from the database: ', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Friend Request",
body: "you have received a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was the notification feature.');
});
});
});
I have read about new APIs on site:
https://firebase.google.com/docs/functions/beta-v1-diff
I think I must change event to context, but I don't know how.
Is anybody know what's the issue?
Thank's for any Help :)
The Firebase documentation on the new data and context shows where the params now live:
The context parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fields eventId, timestamp, eventType, resource, and params.
So to get rid of that error, you'll need to change the first bit of your function to:
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
...
There are more, similar changes that you'll need to make. If you're having a hard time making those yourself, I recommend you check back in with where you got the code from.