【问题标题】:Can Anyone Please Tell me that how to use the function without the button. Function should be triggered automatically谁能告诉我如何在没有按钮的情况下使用该功能。功能应自动触发
【发布时间】:2021-07-12 09:12:01
【问题描述】:

嘿,我正在尝试在我的应用中显示颤动的本地通知。我想要的功能是,每当满足某个条件时,通知功能应该触发然后它应该显示......这是下面的源代码,请帮助我(从这一点开始我不明白该怎么做...... . 请帮帮我)注意:- 该功能应该在不使用任何按钮的情况下完成。只要使用 if else 语句满足条件,_show Notification() 方法就应该运行。

***code***
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final _firestore = FirebaseFirestore.instance;

class NotificationPage extends StatefulWidget {
  static String id = 'notification_screen';
  @override
  _NotificationPageState createState() => _NotificationPageState();
}

class _NotificationPageState extends State<NotificationPage> {
  FlutterLocalNotificationsPlugin fltrNotification;

  @override
  void initState() {
    super.initState();
    var androidInitilize = new AndroidInitializationSettings('app_icon');
    var initilizationsSettings =
        new InitializationSettings(android: androidInitilize);
    fltrNotification = new FlutterLocalNotificationsPlugin();
    fltrNotification.initialize(initilizationsSettings);
    // onSelectNotification: notificationSelected
  }

  // ignore: missing_return
  Future _showNotification() async {
    var androidDetails = new AndroidNotificationDetails(
        "Channel ID", "Expilert", "This is my channel",
        importance: Importance.max);

    var generalNotificationDetails =
        new NotificationDetails(android: androidDetails);

    var scheduledTime = DateTime.now().add(Duration(seconds: 1));

    fltrNotification.schedule(1, "Your product has expired!!!", 'Task',
        scheduledTime, generalNotificationDetails);
  }

  notificationScreen() async {
    await for (var snapshot
        in _firestore.collection('entereditemsdata').snapshots()) {
      for (var itemsPresent in snapshot.docs) {
        print(itemsPresent.data());
        _showNotification();
      }
    }
  }

  static final DateTime now = DateTime.now();
  static final DateFormat formatter = DateFormat('dd/MM/yyyy');
  final String formattedDate = formatter.format(now);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: NotificationStream(
          todayDate: formattedDate,
          function:
              notificationScreen(), // expected error occuring at this point
        ),
      ),
    );
  }
}

class NotificationStream extends StatelessWidget {
  final Function function;
  final String todayDate;
  NotificationStream({this.todayDate, this.function});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _firestore.collection('entereditemsdata').snapshots(),
      // ignore: missing_return

      builder: (context, snapshot) {
        List<NotificationCard> notificationCards = [];
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }

        final items = snapshot.data.docs;

        for (var item in items) {
          final itemData = item.data();
          final productName = itemData['productName'];
          final expiryDate = itemData['expiryDate'];

          final notificationCard = NotificationCard(
            pName: productName,
            eDate: expiryDate,
          );

          // This is the part which you told me to put in the code
          final streamUser =
              _firestore.collection("users").snapshots().asBroadcastStream();
          streamUser.listen((event) {
            event.docs.forEach((user) {
               print(user.data);
              // add condition here and invoke PushNotification
              // ignore: unnecessary_statements
              
              // This is where i am calling the function being passed at constructor
               () => function;
            });
          });

          if (todayDate == expiryDate) {
            notificationCards.add(notificationCard);
          }
        }

        return Expanded(
          child: ListView(
            children: notificationCards,
          ),
        );
      },
    );
  }
}

class NotificationCard extends StatelessWidget {
  final String pName;
  final String eDate;

  NotificationCard({this.pName, this.eDate});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24.0),
          gradient: LinearGradient(colors: [
            Color(0xffFDDB27),
            Color(0xffFDDB27),
          ], begin: Alignment.bottomLeft, end: Alignment.topRight),
          boxShadow: [
            BoxShadow(
              color: Colors.grey,
              blurRadius: 8,
              offset: Offset(0, 3),
            ),
          ],
        ),
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              "$pName has expired on $eDate",
              style: TextStyle(
                color: Color(0xff00B1D2),
                fontFamily: 'Avenir',
                fontSize: 15.0,
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 您能否详细解释一下何时满足某些条件
  • 当来自firestore的文档的一个属性是日期并且在字符串中等于从flutter的DateTime类生成的当前日期匹配时应该调用_showNotification()

标签: function flutter dart localnotification flutter-notification


【解决方案1】:

您可能已经编写了代码来获取应用程序中的文档,匹配日期值并调用此PushNotification

如果没有,您可以将侦听器添加到firebase 集合并像这样侦听值的变化,

final streamUser = Firestore.instance.collection("users").snapshots().asBroadcastStream();
streamUser.listen((event) {
  event.documents.forEach((user) {
    print(user.data);
    // add condition here and invoke PushNotification
  });
});

【讨论】:

  • type 'Future' 不是 type 'Function' 的子类型
  • 你能分享你的代码 sn-p 吗?另外请验证firebase的插件版本。
  • 嘿,再次感谢您的奉献。我已经编辑了这个问题,现在上面的代码是新的,你告诉我把我已经放置的功能放在哪里,还留下了评论,而且我还在我认为可能发生错误的地方发表了评论
  • 版本 =>firebase_core: ^1.0.1 cloud_firestore: ^1.0.1
  • 如果你能解决这个问题,那将是非常可观的
猜你喜欢
  • 1970-01-01
  • 2012-05-21
  • 2022-12-12
  • 2019-11-13
  • 1970-01-01
  • 2023-01-24
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多