如何使用Firebase消息传递将计划通知添加到flutter代码?[副本]

41zrol4v  于 2023-05-18  发布在  Flutter
关注(0)|答案(1)|浏览(105)

此问题已在此处有答案

FCM Schedule delivery date or time of push notification(2个答案)
Schedule FCM Notification using HTTP V1(1个答案)
How can scheduled Firebase Cloud Messaging notifications be made outside of the Firebase Console?(2个答案)
昨天关门了。
这是我的UI

我成功地实现了Firebase通知。当我添加标题、说明和日期并单击该按钮时,会从Firebase向我的设备发送通知。但是,我希望根据我在应用程序中设置的日期和时间接收通知。
通知屏幕截图

我的代码UI代码

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
                              ? 'Next Vaccinated Date'
                              : 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);
                  //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("button"),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

功能

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',

            //want this to when click message open that page (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("Error push notification");
      }
    }
  }

我怎么解决这个问题?

y1aodyip

y1aodyip1#

不幸的是,Firebase Cloud Messaging不支持推送通知调度。但是,您可以使用flutter_local_notifications库在本地安排通知。您可以从Firebase发送数据消息,然后当您的应用收到它时,您可以使用本地通知包来基于scheduledTime安排通知。

相关问题