在不应该调用函数的情况下调用函数

时间:2020-02-26 08:22:56

标签: android flutter dart push-notification scheduling

有一个计划的通知,该通知应该在 5秒后显示。此预定的通知在void initState函数中被调用。我正在使用此package来显示通知。

通知将在 5秒之后显示,因此没有问题。

问题在于,单击通知时应该调用另一个函数。但是在通知甚至还没有出现之前就已经调用了此函数,我不知道这是怎么回事。我尝试了不同的方法来解决此问题,但没有效果。

所有这些发生的代码很低。

class _HomePageState extends State<HomePage> {

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  @override
  void initState() {
    super.initState();
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initNotifSettings = new InitializationSettings(android, null);
    flutterLocalNotificationsPlugin.initialize(initNotifSettings,
        onSelectNotification: whenNotificationSelect);

    showNotification();
  }

  Future whenNotificationSelect(String payload) async {
    print('Payload: $payload');
    Navigator.pushNamed(context, '/notifications');
  }

  showNotification() async {
    var android = new AndroidNotificationDetails(
        'channel id', 'channel name', 'channel description');
    var platform = new NotificationDetails(android, null);

    var scheduledNotificationDateTime =
        DateTime.now().add(Duration(seconds: 2));
    await flutterLocalNotificationsPlugin.schedule(
      0,
      'Good morning!',
      'Greetings from me.',
      scheduledNotificationDateTime,
      platform,
      payload: 'Simple App',
    );
  }
}

注意:单击通知时需要调用函数whenNotificationSelect,但是由于其他原因,我不知道应用程序启动时会立即调用此函数。 我希望 whenNotificationSelect仅在单击通知时才被调用,而不是在应用启动时被调用。

非常感谢您。

1 个答案:

答案 0 :(得分:0)

尝试一下

onSelectNotification:(String payload) => whenNotificationSelect(String payload)

当您不使用(字符串有效负载)时,这意味着该函数也将在null上触发。每当需要传递参数时,请使用(arguments)=> functionName(arguments)