物理返回按钮或滑动不会返回上一页。

huangapple go评论58阅读模式
英文:

Physical back Button or slide doesnt go to previous page

问题

今天在我的Flutter应用程序中遇到了一个奇怪的问题。在安装Firebase消息和Flutter本地通知包,并在iOS和Android上进行了调整后,我发现模拟器和物理设备上的返回按钮以及滑动返回不再返回到前一页,而是将应用程序推到了后台。

我几乎尝试了网上找到的所有方法,比如更改Flutter通道或运行一些flutter clean等等。但都没有效果。

FCM工作正常

这是我的main.dart的一些代码:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await FirebaseApi().initNotifications();
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
  prefs = await SharedPreferences.getInstance();
  Constants.pref = await SharedPreferences.getInstance();

  runApp(MyApp());
}

这是我的FirebaseApi文件:

Future<void> _handleBackgroundNotificationMessage(RemoteMessage message) async {
  if (message.notification != null) return;
  await App.materialKey.currentState?.pushNamed('/appoinments');
}

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;
  final _localNotifications = FlutterLocalNotificationsPlugin();

  final _androidChannel = AndroidNotificationChannel(
    'high_importance_channel',
    'High Importance Notifications',
    description: 'This channel is used for important Notifications',
    importance: Importance.high,
  );

  Future<void> initPushNotifications() async {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      sound: true,
      badge: true,
    );
    FirebaseMessaging.instance.getInitialMessage().then(_handleMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
    FirebaseMessaging.onBackgroundMessage(_handleBackgroundNotificationMessage);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        _localNotifications.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              _androidChannel.id,
              _androidChannel.name,
              channelDescription: _androidChannel.description,
              icon: '@drawable/ic_launcher',
            ),
          ),
          payload: jsonEncode(message.toMap()),
        );
      }
    });
  }

  void _handleMessage(RemoteMessage? message) {
    if (message == null) return;
    App.materialKey.currentState?.pushNamed('/appoinments');
  }

  onClickNotification(payload) async {
    Map<String, dynamic> dat = json.decode(payload);
    App.materialKey.currentState?.pushNamed('/appoinments');
  }

  Future initLocalNotifications() async {
    const iOS = DarwinInitializationSettings();
    const android = AndroidInitializationSettings('@drawable/ic_launcher');
    const settings = InitializationSettings(android: android, iOS: iOS);

    await _localNotifications.initialize(
      settings,
      onDidReceiveNotificationResponse:
          (NotificationResponse notificationResponse) {
        final String? payload = notificationResponse.payload;
        final message = RemoteMessage.fromMap(jsonDecode(payload!));
        _handleMessage(message);
      },
    );

    final platform = _localNotifications.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>();
    await platform?.createNotificationChannel(_androidChannel);
  }

  Future initNotifications() async {
    NotificationSettings settings = await _firebaseMessaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    final fcmToken = await FirebaseMessaging.instance.getToken();
    print(fcmToken);
    print('User granted permission: ${settings.authorizationStatus}');

    initPushNotifications();
    initLocalNotifications();
  }
}

希望这可以帮助你解决问题。如果还有其他疑问,请告诉我。

英文:

Today i experienced a strange problem in my Flutter application. After installing the Firebase messaging and the Flutter local notifications packages, and made the adjustments on iOS and Android, i saw that the back button on emulator and on physical device and the slide back, didnt go to previous page, instead they were pushing the app to the background.

I tried almost everything i found on the web, like change the flutter channel or run some flutter clean etc. Nothing worked.

The FCM works correct

This is some code of my main.dart:

 Future&lt;void&gt; main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseApi().initNotifications();
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
prefs = await SharedPreferences.getInstance();
Constants.pref = await SharedPreferences.getInstance();
runApp(MyApp());
}

And this is my FirebaseApi file:

Future&lt;void&gt; _handleBackgroundNotificationMessage(RemoteMessage message) async {
if (message.notification != null) return;
await   App.materialKey.currentState?.pushNamed(&#39;/appoinments&#39;);
}
class FirebaseApi {
final _firebaseMessaging = FirebaseMessaging.instance;
final _localNotifications = FlutterLocalNotificationsPlugin();
final _androidChannel = AndroidNotificationChannel(
&#39;high_importance_channel&#39;,
&#39;High Importance Notifications&#39;,
description: &#39;This channel is used for important   Notifications&#39;,
importance: Importance.high,
);
Future&lt;void&gt; initPushNotifications() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
sound: true,
badge: true,
);
FirebaseMessaging.instance.getInitialMessage().then(_handleMessage);
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
FirebaseMessaging.onBackgroundMessage(_handleBackgroundNotificationMessage);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// final notification = message.notification;
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
// if (notification == null) return;
if (notification != null &amp;&amp; android != null) {
_localNotifications.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
_androidChannel.id,
_androidChannel.name,
channelDescription: _androidChannel.description,
icon: &#39;@drawable/ic_launcher&#39;,
// other properties...
),
),
payload: jsonEncode(message.toMap()),
);
}
});
}
void _handleMessage(RemoteMessage? message) {
if (message == null) return;
App.materialKey.currentState?.pushNamed(&#39;/appoinments&#39;);
}
onClickNotification(payload) async {
Map&lt;String, dynamic&gt; dat = json.decode(payload);
// if (dat[&#39;type&#39;] == &#39;appointment&#39;) {
//   print(&#39;TRIED TO CALL UPDATE&#39;);
// }
App.materialKey.currentState?.pushNamed(&#39;/appoinments&#39;);
}
Future initLocalNotifications() async {
const iOS = DarwinInitializationSettings();
const android = AndroidInitializationSettings(&#39;@drawable/ic_launcher&#39;);
const settings = InitializationSettings(android: android, iOS: iOS);
await _localNotifications.initialize(
settings,
onDidReceiveNotificationResponse:
(NotificationResponse notificationResponse) {
final String? payload = notificationResponse.payload;
final message = RemoteMessage.fromMap(jsonDecode(payload!));
_handleMessage(message);
// onNotifications.add(payload as String?);
},
);
final platform = _localNotifications.resolvePlatformSpecificImplementation&lt;
AndroidFlutterLocalNotificationsPlugin&gt;();
await platform?.createNotificationChannel(_androidChannel);
// onNotifications.stream.listen(onClickNotification);
}
Future initNotifications() async {
NotificationSettings settings = await _firebaseMessaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
final fcmToken = await FirebaseMessaging.instance.getToken();
print(fcmToken);
print(&#39;User granted permission: ${settings.authorizationStatus}&#39;);
initPushNotifications();
initLocalNotifications();
}
}

答案1

得分: 1

我找到了一个临时解决方案。问题出在Android 13手势和Flutter框架之间的通信上,其中一个会首先处理手势。默认情况下没问题,但我在MainActivity.kt文件中为FCM集成添加了FlutterFragmentActivityFlutterFragmentActivityenableOnBackInvokedCallback:true(在AndroidManifest中)不太兼容。所以我将其临时解决方案设为false,它就能正常工作了。

英文:

I found a temporary solution. The problem was with Android 13 gesture and the communication between Flutter framework, on which of them is gonna handle first the gestures. By default is ok but I added FlutterFragmentActivity in the MainActiviry.kt file for the FCM integration. FlutterFragmentActivity and enableOnBackInvokedCallback:true (in AndroidManifest) aren't working well together. So I added false as a temporary solution and it works.

huangapple
  • 本文由 发表于 2023年6月29日 00:59:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定