简体   繁体   English

想要在 flutter 应用程序中添加新文档时使用一个信号发送推送通知。我应该使用 launchUrl() 方法吗?

[英]Wants to send push notification using one signal when new document is added in the flutter app.Should I use launchUrl() method for it?

Below is the AddNewDocument.dart file.下面是 AddNewDocument.dart 文件。 Whenever I add any document it should show new push notification to the user and should navigate to document details page.每当我添加任何文档时,它都应该向用户显示新的推送通知,并且应该导航到文档详细信息页面。 Is there any method to implement this?有什么方法可以实现吗?

import 'package:AtDocHUB/Controller/DocumentController.dart';
import 'package:AtDocHUB/Model/Document.dart';
import 'package:AtDocHUB/View/Document/DocumentPage.dart';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:form_field_validator/form_field_validator.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:jiffy/jiffy.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat("yyyy-MM-dd").format(now);

//import 'package:flutter_text_form_field/flutter_text_form_field.dart';
class AddNewDocument extends StatefulWidget {
  @override
  State createState() {
    return _AddNewDocumentState();
  }
}

class _AddNewDocumentState extends State<AddNewDocument> {
  late final String date1;

  late String datainput;

  final List<String> items1 = ["Open", "Closed", "Cancel", "Submitted"];
  String? selectedItem;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  

  TextEditingController docTitleController = TextEditingController();
  TextEditingController tokenNoController = TextEditingController();
  
  TextEditingController partyNameController = TextEditingController();
  TextEditingController startDateController = TextEditingController();
  TextEditingController endDateController = TextEditingController();
  late String docType = docTypeController.text;

  final List<String> items = [
    "Residential",
    "Commercial",
  ];
  String? selectedValue;

  List<DropdownMenuItem<String>> _addDividersAfterItems(List<String> items) {
    List<DropdownMenuItem<String>> _menuItems = [];
    for (var item in items) {
      _menuItems.addAll(
        [
          DropdownMenuItem<String>(
            value: item,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                item,
                style: const TextStyle(
                  fontSize: 14,
                ),
              ),
            ),
          ),
          //If it's last item, we will not add Divider after it.
          if (item != items.last)
            const DropdownMenuItem<String>(
              enabled: false,
              child: Divider(),
            ),
        ],
      );
    }
    return _menuItems;
  }

  List<int> _getDividersIndexes() {
    List<int> _dividersIndexes = [];
    for (var i = 0; i < (items.length * 2) - 1; i++) {
      //Dividers indexes will be the odd indexes
      if (i.isOdd) {
        _dividersIndexes.add(i);
      }
    }
    return _dividersIndexes;
  }

  @override
  void dispose() {
    docStatusController.dispose();
    docTypeController.dispose();
    super.dispose();
  }

  @override
  Future<Document>? _futureDocument;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromARGB(255, 3, 87, 156),
        title: Text('Add New Document'),
        leading: IconButton(
            icon: BackButtonIcon(),
            onPressed: () => Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext context) => DocumentPage()))),
      ),
      body:
          //Container(

          SafeArea(
        child: SingleChildScrollView(
          child: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.all(10),
            child: (_futureDocument == null)
                ? buildColumn()
                : buildFutureBuilder(),
          ),
        ),
      ),
    );
  }

  Form buildColumn() {
    return Form(
      key: formKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(
            height: 10,
          ),
          TextFormField(
            minLines: 1,
            maxLines: 3,

            textCapitalization: TextCapitalization.words,

            inputFormatters: [
              FilteringTextInputFormatter.allow(
                  RegExp("[ ',-/ a-z A-Z á-ú Á-Ú 0-9]")),
            ],

            controller: docTitleController,
            style: TextStyle(fontSize: 12),
            keyboardType: TextInputType.multiline,
            decoration: const InputDecoration(
                errorStyle: const TextStyle(fontSize: 0.05),
                border: OutlineInputBorder(),
                hintStyle: TextStyle(fontSize: 12),
                labelStyle: TextStyle(
                  fontSize: 12,
                ),
                labelText: 'Document Title',
                hintText: 'Document title required'),

            // validator: ,
            validator:
                MultiValidator([RequiredValidator(errorText: 'Required*')]),
          ),
          SizedBox(
            height: 20,
          ),
          Wrap(
            children: [
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.4,
                child: TextFormField(
                  style: TextStyle(fontSize: 12),
                  minLines: 1,
                  maxLines: 2,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(14)
                  ],
                  controller: tokenNoController,
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                      errorStyle: const TextStyle(fontSize: 0.05),
                      counterText: "",
                      border: OutlineInputBorder(),
                      hintStyle: TextStyle(fontSize: 12),
                      labelStyle: TextStyle(
                        fontSize: 12,
                      ),
                      labelText: 'Token No',
                      hintText: 'Token no required'),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter token No';
                    } else if (value.length < 14) {
                      return 'Please enter 14 digits number';
                    }
                    return null;
                  },
                ),
              ),
              SizedBox(
                width: 15,
              ),
            
          SizedBox(
            height: 20,
          ),
          SizedBox(
            width: MediaQuery.of(context).size.width,
            child: TextFormField(
              minLines: 1,
              maxLines: 4,
              inputFormatters: [
                LengthLimitingTextInputFormatter(50),
                FilteringTextInputFormatter.allow(RegExp("[a-z A-Z]")),
              ],
              controller: partyNameController,
              keyboardType: TextInputType.name,
              decoration: const InputDecoration(
                  errorStyle: const TextStyle(fontSize: 0.05),
                  border: OutlineInputBorder(),
                  hintStyle: TextStyle(fontSize: 12),
                  labelStyle: TextStyle(
                    fontSize: 12,
                  ),
                  labelText: 'Party Name',
                  hintText: 'Party name required'),
              validator:
                  MultiValidator([RequiredValidator(errorText: 'Required*')]),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              SizedBox(
                width: MediaQuery.of(context).size.width * 0.4,
                child: TextFormField(
                  //  autovalidateMode: AutovalidateMode.onUserInteraction,
                  //FilteringTextInputFormatter.allow(RegExp("[- 0-9]")),
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[- 0-9]")),
                    LengthLimitingTextInputFormatter(10)
                  ],
                  controller: startDateController,
                  keyboardType: TextInputType.datetime,
                  decoration: const InputDecoration(
                    errorStyle: const TextStyle(fontSize: 0.05),
                    prefixIcon: Icon(Icons.calendar_month),
                    border: OutlineInputBorder(),
                    hintStyle: TextStyle(fontSize: 12),
                    labelStyle: TextStyle(
                      fontSize: 12,
                    ),
                    labelText: 'Start Date',
                    hintText: 'yyyy-MM-dd',
                  ),
                  onTap: () async {
                    DateTime? pickedDate = await showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime(
                          1991), //DateTime.now() - not to allow to choose before today.
                      lastDate: DateTime(2101),
                      // onConfirm:widget.onChanged,
                    ).then((pickedDate) {
                      if (pickedDate != null) {
                        // print(
                        // pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                        String formattedDate =
                            DateFormat('yyyy-MM-dd').format(pickedDate);

                        print(formattedDate);

                        setState(() {
                          startDateController.text = formattedDate;
                          //set output date to TextField value.
                        });
                        print(startDateController.text);
                      } else {
                        print("Date is not selected");
                      }
                    });
                    final int dur = int.parse(durationController.text);
                    var stDate = DateTime.parse(startDateController.text);

                    var jiffy = Jiffy(stDate).add(
                      months: dur,
                      days: -1,
                      // days: 1095,
                    );
                    DateTime d = jiffy.dateTime;
                    String s = jiffy.format('yyyy-MM-dd');
                    setState(() {
                      endDateController.text = s.toString();
                    });
                  },

                  validator: MultiValidator(
                      [RequiredValidator(errorText: 'Required*')]),
                ),
              ),
              SizedBox(
                width: 13,
              ),
              SizedBox(
                // height: MediaQuery.of(context).size.height * 0.06,
                width: MediaQuery.of(context).size.width * 0.5,
                child: TextFormField(
                  // maxLength: 8,
                  // autovalidateMode: AutovalidateMode.onUserInteraction,
                  autofocus: false,
                  controller: endDateController,
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[- 0-9]")),
                    LengthLimitingTextInputFormatter(10)
                  ],
                  keyboardType: TextInputType.datetime,
                  decoration: const InputDecoration(
                      errorStyle: const TextStyle(fontSize: 0.05),
                      // prefixIcon: Icon(Icons.calendar_month),
                      counterText: "",
                      border: OutlineInputBorder(),
                      hintStyle: TextStyle(fontSize: 12),
                      labelStyle: TextStyle(
                        fontSize: 12,
                      ),
                      labelText: 'End Date',
                      hintText: ' yyyy-MM-dd'),
                  onTap: () async {},

                  validator: MultiValidator(
                      [RequiredValidator(errorText: 'Required*')]),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 20,
          ),
          SizedBox(
            //  height: MediaQuery.of(context).size.height * 0.06,
            width: MediaQuery.of(context).size.width,
            child: TextFormField(
              minLines: 1,
              maxLines: 4,

              // autovalidateMode: AutovalidateMode.onUserInteraction,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp("[a-z A-Z 0-9]")),
                // FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(50)
              ],
              controller: rentDescController,
              keyboardType: TextInputType.multiline,
              decoration: const InputDecoration(
                  errorStyle: const TextStyle(fontSize: 0.05),
                  border: OutlineInputBorder(),
                  hintStyle: TextStyle(fontSize: 12),
                  labelStyle: TextStyle(
                    fontSize: 12,
                  ),
                  labelText: 'Rent Description',
                  hintText: 'Rent Description required'),
              // validator:
              //     MultiValidator([RequiredValidator(errorText: 'Required*')]),
            ),
          ),
          SizedBox(
            height: 20,
          ),
          Container(

              //alignment: Alignment.center,
              height: 35,
              width: 200,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Color.fromARGB(255, 3, 89, 168),
              ),
              child: ElevatedButton(
                onPressed: () {
                  formKey.currentState?.validate();
                  final isValidForm = formKey.currentState!.validate();
                  if (isValidForm) {
                    //formKey.currentState?.validate();
                    // final int docId = int.parse(docIdController.text).toInt();
                    final String docTitle = docTitleController.text;
                    final int tokenNo =
                        int.parse(tokenNoController.text).toInt();
                    //final String tokenNo = tokenNoController.text;
                    final String partyName = partyNameController.text;
                    final String startDate = startDateController.text;
                    final String endDate = endDateController.text;

                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (BuildContext context) => DocumentPage()));

                    setState(() {
                      _futureDocument = createDocument(
                        // docId,
                        docTitle,
                        tokenNo,
                       startDate,
                        endDate,
                        //  createdAt,
                      );
                    });
                    // }
                  }
                },
                child: const Text("Save"),
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(
                        Color.fromARGB(255, 3, 89, 168))),
              ))
        ],
      ),
    );
    //])
    //);
  }

  FutureBuilder<Document> buildFutureBuilder() {
    return FutureBuilder<Document>(
      future: _futureDocument,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text(snapshot.data!.docTitle);
        } else if (snapshot.hasError) {
          return Text('${snapshot.error}');
        }

        return const CircularProgressIndicator();
      },
    );
  }
}

Below is the main.dart file where I have initialised App Id and other required things.Push Notification is coming in app properly and when I tap on the notification it opens the application.下面是 main.dart 文件,我在其中初始化了 App Id 和其他必需的东西。推送通知正确地进入应用程序,当我点击通知时它会打开应用程序。 But i wants to show push notification when the new document is added to the app and when user tap on that particular notification it should navigate user to the document details page.I have also attached AddNewDocumentFile.dart.但我想在新文档添加到应用程序时显示推送通知,当用户点击该特定通知时,它应该将用户导航到文档详细信息页面。我还附上了 AddNewDocumentFile.dart。

import 'package:flutter/material.dart';

import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'View/LoginPage.dart';
import 'View/homePageAdmin.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedPrefService.init();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class SharedPrefService {
  static late SharedPreferences pref;

  static Future<void> init() async {
    pref = await SharedPreferences.getInstance();
    var usrEmail = pref.getString('email');
  }
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    OneSignal.shared.setAppId('e89acaa4-5388-4e3a-bd69-44d197bdcbd7');
    OneSignal.shared
        .promptUserForPushNotificationPermission()
        .then((accepted) {});
    
  }

  @override
  Widget build(BuildContext context) {
    var usrEmail = SharedPrefService.pref.getString('email');

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
       
        primarySwatch: Colors.indigo,
      ),
      home: usrEmail == null ? LoginPage() : homePageAdmin(),
    );
  }
}

You just need to call the OneSignal.shared.postNotification(notification);您只需要调用OneSignal.shared.postNotification(notification); after your createDocument function completes.在您的createDocument function 完成后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从用户应用程序向管理应用程序发送推送通知 - Flutter - Send Push notification from user app to admin app - Flutter Flutter,当我从 firebase 消息发送通知时出现此错误并且我的应用程序冻结 - Flutter, when i send notification from firebase messaging i get this error and my app freeze Flutter Firebase 消息 - 应用打开时不显示推送通知 - Flutter Firebase messaging - push notification is not showing when app is open Flutter iOS 应用程序在前台时的 FCM 推送通知 - Flutter FCM push notification for iOS when app is in foreground 如何折叠 Flutter 中的通知? 使用本地推送通知插件和 CloudFunctions - How can I collapse notification in Flutter? using Local Push Notification plugin and CloudFunctions 在使用 FirebaseAuth 时,我是否应该在重新加载 Flutter web 应用程序时直接使用 IndexedDB 来确定身份验证 state? - Should I consume IndexedDB directly when reloading a Flutter web app to determine auth state when using FirebaseAuth? Flutter - Firebase 使用 firebase 消息传递成功但未收到通知的推送通知 - Flutter - Firebase push notification using firebase messaging success but not get notification 单击推送通知时如何处理 Flutter 中的屏幕导航? - How to handle screen navigation in Flutter when clicking on a Push Notification? 对于使用大量图像的 flutter 应用程序,我应该使用哪个数据库? - Which database should I use for my flutter app using lots of images? 如何使用谷歌 firebase 发送移动推送通知 - how to send mobile push notification using google firebase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM