Flutter:单击通知后无法导航到任何小部件

时间:2019-05-21 14:54:50

标签: flutter push-notification alarmmanager

我正在使用android_alarm_manager按计划推送通知。推送通知工作正常。但是,当我单击 Push notification 时,它正在调用onSelectNotification()方法,该方法将在其中打印推送通知有效内容,然后导航到新的Widget

此处成功打印了推送通知有效内容,但导航无法正常工作。通过调试,我看到:

  

_globalKey.currentContext为空

有人可以告诉我代码有什么问题吗,或者有什么更好的方法来解决这个问题?

import 'dart:isolate';

import 'package:flutter/material.dart';
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:daily_quotes/helpers/second_page.dart';
import 'package:daily_quotes/helpers/local_notification_helper.dart';

final notifications = FlutterLocalNotificationsPlugin();

GlobalKey _globalKey = new GlobalKey();

void pushNotification() async {
  showIconNotification(_globalKey.currentContext, notifications,
      icon: Image.asset("assets/screen.png"),
      title: "Some title",
      body: "HelloWorld",
      id: 40);
}

Future onSelectNotification(String payload) async {
  //This one is getting printed
  print("Payload : " + payload);
  //But the redirection is not working. As _globalKey.currentContext is null
  await Navigator.push(_globalKey.currentContext,
      MaterialPageRoute(builder: (context) => SecondPage(payload: payload)));
} 


void main() async {
  final settingsAndroid = AndroidInitializationSettings('@mipmap/screen');
  final settingsIOS = IOSInitializationSettings(
      onDidReceiveLocalNotification: (id, title, body, payload) =>
          onSelectNotification(payload));
  notifications.initialize(InitializationSettings(settingsAndroid, settingsIOS),
      onSelectNotification: onSelectNotification);
  final int helloAlarmID = 0;
  await AndroidAlarmManager.initialize();

  runApp(MyApp());

  await AndroidAlarmManager.periodic(
      const Duration(seconds: 10), helloAlarmID, pushNotification);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Daily Quotes',
        theme: ThemeData(
          primarySwatch: Colors.pink,
        ),
        home: CategoryPage());
  }
}

0 个答案:

没有答案