如何在我的Flutter代码中使用Firebase消息添加计划通知?

huangapple go评论60阅读模式
英文:

How I add schedule notification to my flutter code using Firebase messaging?

问题

以下是代码的翻译部分:

DateTime now = new DateTime.now();
void showDatePickerNextVaccinationDate() {
  DateTime mindate = DateTime(now.year, now.month, now.day);
  DateTime maxdate = DateTime(now.year + 12, now.month, now.day);
  showCupertinoModalPopup(
    context: context,
    builder: (BuildContext builder) {
      return Container(
        height: MediaQuery.of(context).copyWith().size.height * 0.25,
        color: Colors.white,
        child: CupertinoDatePicker(
          maximumYear: now.year + 12,
          minimumYear: now.year,
          mode: CupertinoDatePickerMode.dateAndTime,
          initialDateTime: mindate,
          onDateTimeChanged: (value) {
            if (value != nextDate) {
              setState(() {
                nextDate = value;
                //calAge();
              });
            }
          },
          maximumDate: maxdate,
          minimumDate: mindate,
        ),
      );
    },
  );
}
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextFormField(
            controller: title,
          ),
          TextFormField(
            controller: body,
          ),
          GestureDetector(
            onTap: showDatePickerNextVaccinationDate,
            child: SizedBox(
              width: 500,
              height: 70,
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black),
                  borderRadius: BorderRadius.circular(15),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(
                        left: 3,
                        top: 20,
                        bottom: 10,
                      ),
                      child: Text(
                        nextDate == null
                            ? '下次疫苗接种日期'
                            : DateFormat('HH MMMM dd yyyy ').format(nextDate!),
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w300,
                        ),
                      ),
                    ),
                    Icon(
                      Icons.arrow_drop_down,
                      color: Colors.grey[700],
                      size: 30.0,
                    ),
                  ],
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              String name = "User1";
              String titleText = title.text;
              String bodyText = body.text;
              String selectedNextDate = nextDate.toString();
              if (name != "") {
                DocumentSnapshot snap = await FirebaseFirestore.instance
                    .collection("UserTokens")
                    .doc(name)
                    .get();
                String token = snap['token'];
                print(token);
                //调用sendPushMessage
                sendPushMessage(token, titleText, bodyText, selectedNextDate);
              }
            },
            child: Container(
              margin: EdgeInsets.all(20),
              height: 40,
              width: 200,
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: Colors.redAccent.withOpacity(0.5),
                  )
                ],
              ),
              child: Center(
                child: Text("按钮"),
              ),
            ),
          )
        ],
      ),
    ),
  );
}
void sendPushMessage(String token, String body, String title, String selectedNextDate) async {
  try {
    await http.post(
      Uri.parse('https://fcm.googleapis.com/fcm/send'),
      headers: <String, String>{
        'Content-Type': 'application/json',
        'Authorization': 'key=....',
      },
      body: jsonEncode(<String, dynamic>{
        'priority': 'high',

        //希望在点击消息时打开该页面(payload function)
        'data': <String, dynamic>{
          'click_action': 'Test_Notification',
          'status': 'done',
          'body': '$body $selectedNextDate',
          'title': title,
          "isScheduled": "true",
          "scheduledTime": "2023-05-17 18:44:00"
        },
        "notification": <String, dynamic>{
          "title": title,
          "body": '$body $selectedNextDate',
          "android_channel_id": "dbfood",
          "isScheduled": "true",
          "scheduledTime": "2023-05-17 18:44:00"
        },
        "to": token,
      }),
    );
  } catch (e) {
    if (kDebugMode) {
      print("错误的推送通知");
    }
  }
}

希望这些翻译有帮助!如果您有任何其他问题,请随时提问。

英文:

Here it is my UI

如何在我的Flutter代码中使用Firebase消息添加计划通知?

I successfully implemented Firebase notifications. When I add a title, description, and date, and click the button, a notification is sent from Firebase to my device. However, I want to receive a notification based on the date and time I set within the application.

notification screenshot

如何在我的Flutter代码中使用Firebase消息添加计划通知?

my codeUI code


DateTime now = new DateTime.now();
void showDatePickerNextVaccinationDate() {
DateTime mindate = DateTime(now.year , now.month, now.day);
DateTime maxdate = DateTime(now.year + 12, now.month, now.day);
showCupertinoModalPopup(
context: context,
builder: (BuildContext builder) {
return Container(
height: MediaQuery.of(context).copyWith().size.height * 0.25,
color: Colors.white,
child: CupertinoDatePicker(
maximumYear: now.year + 12,
minimumYear: now.year ,
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: mindate,
onDateTimeChanged: (value) {
if (value != nextDate) {
setState(() {
nextDate = value;
//calAge();
});
}
},
maximumDate: maxdate,
minimumDate: mindate,
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: title,
),
TextFormField(
controller: body,
),
GestureDetector(
onTap: showDatePickerNextVaccinationDate,
child: SizedBox(
width: 500,
height: 70,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(15),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: EdgeInsets.only(
left: 3,
top:20,
bottom: 10,
),
child: Text(
nextDate == null
? &#39;Next Vaccinated Date&#39;
: DateFormat(&#39;HH MMMM dd yyyy &#39;)
.format(nextDate!),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w300,
),
),
),
Icon(
Icons.arrow_drop_down,
color: Colors.grey[700],
size: 30.0,
),
],
),
),
),
),
GestureDetector(
onTap: () async {
String name = &quot;User1&quot;;
String titleText = title.text;
String bodyText = body.text;
String selectedNextDate  = nextDate.toString();
if (name != &quot;&quot;) {
DocumentSnapshot snap = await FirebaseFirestore.instance
.collection(&quot;UserTokens&quot;)
.doc(name)
.get();
String token = snap[&#39;token&#39;];
print(token);
//call sendPushMessage
sendPushMessage(token, titleText, bodyText,selectedNextDate);
}
},
child: Container(
margin: EdgeInsets.all(20),
height: 40,
width: 200,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.redAccent.withOpacity(0.5),
)
]),
child: Center(
child: Text(&quot;button&quot;),
),
),
)
],
),
),
);
}
}

function

void sendPushMessage(String token, String body, String title,String selectedNextDate) async {
try {
await http.post(Uri.parse(&#39;https://fcm.googleapis.com/fcm/send&#39;),
headers: &lt;String, String&gt;{
&#39;Content-Type&#39;: &#39;application/json&#39;,
&#39;Authorization&#39;: &#39;key=....&#39;,
},
body: jsonEncode(&lt;String, dynamic&gt;{
&#39;priority&#39;: &#39;high&#39;,
//want this to when click message open that page (payload function)
&#39;data&#39;: &lt;String, dynamic&gt;{
&#39;click_action&#39;: &#39;Test_Notification&#39;,
&#39;status&#39;: &#39;done&#39;,
&#39;body&#39;: &#39;$body $selectedNextDate&#39;,
&#39;title&#39;: title,
&quot;isScheduled&quot; : &quot;true&quot;,
&quot;scheduledTime&quot; : &quot;2023-05-17 18:44:00&quot;
},
&quot;notification&quot;: &lt;String, dynamic&gt;{
&quot;title&quot;: title,
&quot;body&quot;:&#39;$body $selectedNextDate&#39;,
&quot;android_channel_id&quot;: &quot;dbfood&quot;,
&quot;isScheduled&quot; : &quot;true&quot;,
&quot;scheduledTime&quot; : &quot;2023-05-17 18:44:00&quot;
},
&quot;to&quot;: token,
}));
} catch (e) {
if (kDebugMode) {
print(&quot;Error push notification&quot;);
}
}
}

How I solve this ?

答案1

得分: 1

Firebase Cloud Messaging不支持推送通知的调度。但是,你可以使用flutter_local_notifications库在本地调度通知。你可以从Firebase发送一个数据消息,然后当你的应用接收到它时,使用本地通知包根据scheduledTime来调度通知。

英文:

Unfortunately, Firebase Cloud Messaging does not support push notifications scheduling. However, you can schedule notifications locally with flutter_local_notifications library. You can send a data message from Firebase then when your app receives it, you use the local notifications package to schedule the notification based on scheduledTime.

huangapple
  • 本文由 发表于 2023年5月17日 21:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定