Flutter: как проверить, открыто ли приложение, щелкнув push-уведомление или щелкнув значок запуска приложения

Я пытаюсь выяснить, открывается ли приложение, щелкнув push-уведомление или щелкнув значок средства запуска приложения. Сценарий таков: я хочу проверить, открывается ли приложение, нажав push-уведомление, а затем я загружу данные на главный экран из кеша другого мудрый, мне нужно получить данные из API.

я использую метод getInitialMessage(), но в моем случае он не работает

вот мой код

   Class NotificationService{ 
String? msg;
 bool fromNotification = false;
 final _firebaseMessaging = FirebaseMessaging.instance;
 Future<void> initNotification() async 
{
 RemoteMessage? initialMessage = await _firebaseMessaging.getInitialMessage(); 
 if (initialMessage != null) 
{ msg = initialMessage.toString();
 fromNotification = true;
 }
 }
 }

293
2

Ответы:

Этого можно добиться, установив флаг во время запуска приложения. Это можно сделать в классе PushNotificationHandler, используя функцию ниже.

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  // Handle notification clicks here
  // Set a flag or send a message to the app indicating it was opened from a notification
});

Предполагая, что ваш первый экран называется MyHomePage, вы можете передать ему флаг, как показано ниже:

final bool openedFromNotification; // declare the variable 
MyHomePage({this.openedFromNotification = false}); //Pass the variable into the method.

Использование метода getInitialMessage():

// Create a nullable RemoteMessage variable
RemoteMessage? initialMessage = await _firebaseMessaging.getInitialMessage();
// Check if initialMessage has a value
if (initialMessage != null) {
// Set a flag or send a message at this point
}

Затем вы можете использовать флаг по своему усмотрению.


Решено

Я добился этого с помощью функции onMessageOpenedApp. Смотрите мой код ниже.

Определите класс PushNotificationHandler, как показано ниже:

class PushNotificationHandler {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final localNotifications = FlutterLocalNotificationsPlugin();
bool _openedFromNotification = false;
// Android Channel
final androidChannel = const AndroidNotificationChannel(
  'test_channel_name', "Test Channel",
  description: "This is a TEST Channel",
  importance: Importance.defaultImportance);

Future<bool> initialize() async {
// Initialize Firebase Messaging
await _firebaseMessaging.requestPermission();

// Get the FCM token to use when sending notifications
String? fcmToken;

if (Platform.isIOS) {
  fcmToken = await _firebaseMessaging.getAPNSToken() ?? "";
  final platform = localNotifications.resolvePlatformSpecificImplementation<
      IOSFlutterLocalNotificationsPlugin>();
} else if (Platform.isAndroid) {
  fcmToken = await _firebaseMessaging.getToken() ?? "";
  final platform = localNotifications.resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>();
  await platform?.createNotificationChannel(androidChannel);
}

// display the token so you can use it to send notifications
if (fcmToken != null) {
  print('FCMToken: ${fcmToken}');
}

// Handle notifications when the app is in the background
FirebaseMessaging.onBackgroundMessage(_handleBackgroundMessage);

// Handle notifications when the app is in the foreground
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  
});

// Handle notification clicks when the app is terminated
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  // Handle notification clicks here
  // Set a flag or send a message to the app indicating it was opened from a notification
  _openedFromNotification = true;
});

return _openedFromNotification;
}

Функция Initialize() вернет bool.

Определите свое приложение, как показано ниже:

class MyNotificationApp extends StatefulWidget {
@override
_MyNotificationAppState createState() => _MyNotificationAppState();
}
class _MyNotificationAppState extends State<MyNotificationApp> {
final PushNotificationHandler _pushNotificationHandler =
  PushNotificationHandler();
bool _appOpenedFromNotification = false;
@override
void initState() {
super.initState();
print('OPENING_APP');
_initializePushNotifications();
}
// Initialize the notifications
Future<void> _initializePushNotifications() async {
// Wait for the initialization to complete
bool result = await _pushNotificationHandler.initialize();
setState(() {
  _appOpenedFromNotification = result;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
  title: 'My App',
  home: MyHomePage(appOpenedFromNotification: _appOpenedFromNotification),
);
}
}

В виджете MyHomePage я распечатываю, как было открыто приложение.

class MyHomePage extends StatelessWidget {
final bool appOpenedFromNotification;
const MyHomePage({super.key, required this.appOpenedFromNotification});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
  ),
  body: Center(
    child: Text(appOpenedFromNotification
        ? 'Opened from notification'
        : 'Opened from launcher'),
  ),
);
}
}

Это должно решить вашу проблему.