lets Code
lets Code

Reputation: 81

Flutter firebase messaging not working when app is killed

This is my main.dart. I'm receiving notifications when app is running in foreground or in background but when app is terminated/closed I don't get any notification. I have searched every where. But not a single blog or post helped me.

import 'dart:async';
​
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:io' show Platform;
​
void main() {
  runApp(MyApp());
}
​
void DialogBox(String Title, String message, context, Function action) {
  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ),
          backgroundColor: Color(0XffC75A53),
          title: Text(
            Title,
            textAlign: TextAlign.center,
            style: TextStyle(
                color: Color(0xFF111328), fontWeight: FontWeight.w900),
          ),
          content: Text(
            message,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.white,
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text(
                'OK',
                style: TextStyle(
                  color: Color(0xFF111328),
                ),
              ),
              onPressed: action,
            ),
          ],
        );
      });
}
​
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
​
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
​
  final String title;
​
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
​
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
​
  final FirebaseMessaging _fcm = FirebaseMessaging();
  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  StreamSubscription iosSubscription;
​
  @override
  void initState() {
    super.initState();
​
    var android = AndroidInitializationSettings('mipmap/ic_launcher');
    var ios = IOSInitializationSettings();
    var platform = InitializationSettings(android, ios);
    _flutterLocalNotificationsPlugin.initialize(platform);
​
    if (Platform.isIOS) {
      iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
        print(data);
      });
​
      _fcm.requestNotificationPermissions(IosNotificationSettings());
    }
​
    _fcm.configure(
      // app in fg
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        showNotification(message);
        DialogBox("Data", message.toString(), context, () {
          Navigator.pop(context);
        });
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message"); // app terminated
//        Navigator.pushReplacementNamed(context, HomeScreen.id);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        DialogBox("Data", message.toString(), context, () {
          Navigator.pop(context);
        });
//        Navigator.pushReplacementNamed(context, HomeScreen.id);
//        Navigator.of(context).pushNamed(message['data']['status']);
      },
    );
  }
​
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
​
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
​
  showNotification(Map<String, dynamic> message) async {
    var android = AndroidNotificationDetails(
        'channel_id', 'channel_name', 'channel_descriptions');
    var ios = IOSNotificationDetails();
    var platform = NotificationDetails(android, ios);
    await _flutterLocalNotificationsPlugin.show(
        0,
        message['notification']['title'].toString(),
        message['notification']['body'].toString(),
        platform);
  }
​
  @override
  void dispose() {
    if (iosSubscription != null) iosSubscription.cancel();
    super.dispose();
  }
}

Upvotes: 3

Views: 2499

Answers (2)

Guilherme Gabanelli
Guilherme Gabanelli

Reputation: 566

FlutterFire package have some limitations, in the version 9.0.2 we can see this in the docs:

On iOS, if the user swipes away the application from app Switcher, it must be manually reopened again for background messages to start working again.

On Android, if the user force quits the app from device settings, it must be manually reopened again for messages to start working.

I think the first one could be whats is happen with you.

Source: FlutterFire Docs

Upvotes: 1

lets Code
lets Code

Reputation: 81

found it! it was device issue some devices doesn't support some apps background notifications. run your app on other device and it will work as expected

Upvotes: 2

Related Questions