首页 > 解决方案 > 应用打开时在整个应用中显示 FCM 通知 (Flutter)

问题描述

我现在正在使用 FCM 向我的设备发送推送通知,并且运行良好。但是,当应用程序打开时,我只有在该特定页面中时才会执行 onResume。无论用户在哪个页面(或类)上,我都想在顶部显示通知。基本上我希望通知在全球范围内显示(显示弹出窗口)。任何帮助,将不胜感激。这是显示通知的页面中的代码。

if (Platform.isIOS) {
     iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
    _saveDeviceToken();
   });

  _fcm.requestNotificationPermissions(IosNotificationSettings());
} else {
  _saveDeviceToken();
}

_fcm.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
    var temp = message['notification'];
    setState(() {
      title.add(temp['title']);
      body.add(temp['body']);
    });
   
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ListTile(
          title: Text(message['notification']['title']),
          subtitle: Text(message['notification']['body']),
        ),
        actions: <Widget>[
          FlatButton(
            color: const Color(0xFF650572),
            child: Text('Ok'),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => MessageHandler()));
    // TODO optional
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
    Navigator.push(context,
        MaterialPageRoute(builder: (context) => MessageHandler()));
    // TODO optional
  },
);

}

标签: androidflutternotificationsfirebase-cloud-messaging

解决方案


将您的 MaterialApp 包装在一个包装类中......让我们称之为 FCMWrapper。

class FCMWrapper extends StatefulWidget {
  final Widget child;

  const FCMWrapper({Key key, this.child}) : super(key: key);

  @override
  _FCMWrapperState createState() => _FCMWrapperState();
}

class _FCMWrapperState extends State<FCMWrapper> {
  @override
  Widget build(BuildContext context) {
    return Consumer<YourObservable>(
      builder: (context, yourObservable, _) {
        if (yourObservable != null && yourObservable.isNotEmpty) {
          Future(
            () => navigatorKey.currentState.push(
              PushNotificationRoute(
                  child: YourViewOnNotification(),
              )),
            ),
          );
        }
        return widget.child;
      },
    );
  }
}

我已经将我的数据存储在一个单独的类的可观察对象中。因此,当我收到通知时,我会更新我的 observable。由于我们正在使用该 observable,因此将调用 PushNotificationRoute。

PushNotificationRoute 只是一个扩展 ModalRoute 的类。

class PushNotificationRoute extends ModalRoute {
  final Widget child;

  PushNotificationRoute({this.child});

  ... //Override other methods to your requirement

  //This is important
  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return SafeArea(
      child: Builder(builder: (BuildContext context) {
        return child;
      }),
    );
  }

  ...
  @override
  Duration get transitionDuration => Duration(milliseconds: 200);
}

现在在 main.dart 中声明一个全局键,如

var navigatorKey = GlobalKey<NavigatorState>();

并像包装你的 MaterialApp

...

FCMWrapper(
          child: MaterialApp(
            navigatorKey: navigatorKey,
            title: 'Your App',

...

因此,现在每次收到通知时,您的 observable 都应该更新并推送一条模态路线,该路线将显示在应用程序的任何位置。


推荐阅读