【问题标题】:How to show flutter local notification while receiving push notification on foreground?如何在前台接收推送通知时显示颤振本地通知?
【发布时间】:2020-06-28 12:25:59
【问题描述】:

目前,我正在使用警报对话框来显示通知,同时在应用程序处于前台时接收推送通知。但我想展示一些非侵入性的东西,比如颤动的本地通知。如何在我的应用程序中实现它?这是我当前的实现:

FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  @override
  void initState() {
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            content: ListTile(
              title: Text(message['notification']['title']),
              subtitle: Text(message['notification']['body']),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Ok'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
        print("onMessage: $message");
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        Navigator.pushNamed(context, '/notify');
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
}

【问题讨论】:

    标签: flutter dart firebase-cloud-messaging


    【解决方案1】:

    由于我没有得到答案,所以我自己尝试并弄清楚了。

    不要忘记将flutter_local_notifications 库添加到您的项目中以使用此代码 https://pub.dev/packages/flutter_local_notifications

    经过测试并适用于 Android

    FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
      @override
      void initState() {
    var initializationSettingsAndroid =
            new AndroidInitializationSettings('@mipmap/ic_launcher');
        var initializationSettingsIOS = new IOSInitializationSettings();
        var initializationSettings = new InitializationSettings(
            initializationSettingsAndroid, initializationSettingsIOS);
        flutterLocalNotificationsPlugin.initialize(initializationSettings,
            onSelectNotification: onSelectNotification);
        _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
            showNotification(
                message['notification']['title'], message['notification']['body']);
            print("onMessage: $message");
          },
          onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch: $message");
            Navigator.pushNamed(context, '/notify');
          },
          onResume: (Map<String, dynamic> message) async {
            print("onResume: $message");
          },
        );
    }
    Future onSelectNotification(String payload) async {
        showDialog(
          context: context,
          builder: (_) {
            return new AlertDialog(
              title: Text("PayLoad"),
              content: Text("Payload : $payload"),
            );
          },
        );
      }
    void showNotification(String title, String body) async {
        await _demoNotification(title, body);
      }
    
      Future<void> _demoNotification(String title, String body) async {
        var androidPlatformChannelSpecifics = AndroidNotificationDetails(
            'channel_ID', 'channel name', 'channel description',
            importance: Importance.Max,
            playSound: true,
            sound: 'sound',
            showProgress: true,
            priority: Priority.High,
            ticker: 'test ticker');
    
        var iOSChannelSpecifics = IOSNotificationDetails();
        var platformChannelSpecifics = NotificationDetails(
            androidPlatformChannelSpecifics, iOSChannelSpecifics);
        await flutterLocalNotificationsPlugin
            .show(0, title, body, platformChannelSpecifics, payload: 'test');
      }
    

    它就像一个魅力。希望能帮助别人:)

    【讨论】:

    • 非常感谢:)。我会在 iOS 上尝试一下,如果它也能用,我会告诉你
    • @rebar 这在IOS上对你有用吗?我正在尝试做类似的事情,但仍然遇到一些麻烦。
    • 感谢您的回答!不要忘记将 flutter_local_notifications 库添加到您的项目中以使用此代码。
    • @AliHaider 我认为现在您必须在 android/app/src/main/res/raw/sound.mp3 内的 raw 文件夹中添加声音。现在是sound:RawResourceAndroidNotificationSound('sound')
    • @Rocx 不,你不需要到处配置它。但最好在第一个屏幕上配置它。如果有登录页面,可以在用户登录成功后进行配置。重点是只做一次。并使用 get_it 库使函数单例,以确保只有一个通知处理程序实例正在运行。
    【解决方案2】:

    我使用静态方法 init() 创建了这个类,并从我的应用程序首页的 initState 调用它一次

    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'my_channel', // id
      'My Channel', // title
      'Important notifications from my server.', // description
      importance: Importance.high,
    );
    
    class Notifications {
      static Future init() async {
        await Firebase.initializeApp();
        FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
        
        final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
            FlutterLocalNotificationsPlugin();
    
        await flutterLocalNotificationsPlugin
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.createNotificationChannel(channel);
    
        await FirebaseMessaging.instance
            .setForegroundNotificationPresentationOptions(
          alert: true,
          badge: true,
          sound: true,
        );
    
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          RemoteNotification notification = message.notification;
          AndroidNotification android = message.notification?.android;
          if (notification != null && android != null) {
            flutterLocalNotificationsPlugin.show(
                notification.hashCode,
                notification.title,
                notification.body,
                NotificationDetails(
                  android: AndroidNotificationDetails(
                    channel.id,
                    channel.name,
                    channel.description,
                    icon: 'some_icon_in_drawable_folder',
                  ),
                ));
          }
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2021-01-28
      • 2020-06-26
      • 2021-07-14
      • 2021-11-04
      • 2021-12-28
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多