gpt4 book ai didi

flutter - 访问 BuildContext 以从推送通知服务 (Flutter) 导航

转载 作者:行者123 更新时间:2023-12-05 01:24:18 27 4
gpt4 key购买 nike

我正在努力了解如何在 flutter 中选择通知时从推送通知类导航。我需要访问 BuildContext 或以某种方式找出一种方法来告诉我的应用程序在没有它的情况下导航。

我的代码如下所示:

主.dart

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await PushNotificationService().setupInteractedMessage();
runApp(const MyApp());
}

Future awaitDeepLink() async {
StreamSubscription _sub;
try {
await getInitialLink();
_sub = uriLinkStream.listen((Uri uri) {
runApp(MyApp(uri: uri));
}, onError: (err) {

});
} on PlatformException {
print("PlatformException");
} on Exception {
print('Exception thrown');
}
}

class MyApp extends StatelessWidget {
final Uri uri;

static final FirebaseAnalytics analytics = FirebaseAnalytics.instance;

const MyApp({Key key, this.uri}) : super(key: key);

@override
Widget build(BuildContext context) {
return OverlaySupport(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);

if (!currentFocus.hasPrimaryFocus &&
currentFocus.focusedChild != null) {
FocusManager.instance.primaryFocus.unfocus();
}
},
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: buildThemeData(),
home: CheckAuth(uri: uri),
),
),
);
}
}

PushNotificationService.dart

class PushNotificationService {
Future<void> setupInteractedMessage() async {
RemoteMessage initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
String token = await FirebaseMessaging.instance.getToken();

var storage = const FlutterSecureStorage();
storage.write(key: "fcm_token", value: token);

if (initialMessage != null) {
print(initialMessage.data['type']);
}

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print("message opened app:" + message.toString());
});

await enableIOSNotifications();
await registerNotificationListeners();
}

registerNotificationListeners() async {
AndroidNotificationChannel channel = androidNotificationChannel();

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);

var androidSettings =
const AndroidInitializationSettings('@mipmap/ic_launcher');

var iOSSettings = const IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
);

var initSettings = InitializationSettings(
android: androidSettings,
iOS: iOSSettings,
);

flutterLocalNotificationsPlugin.initialize(
initSettings,
onSelectNotification: onSelectNotification,
);

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,
icon: android.smallIcon,
playSound: true,
),
),
payload: json.encode(message.data),
);
}
});

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
print("onMessageOpenedApp: $message");

if (message.data != null) {
print(message.data);
}
});

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}

Future onSelectNotification(String payload) async {
Map data = json.decode(payload);

if (data['type'] == 'message') {
// NEED TO ACCESS CONTEXT HERE
// Navigator.push(
// navigatorKey.currentState.context,
// CupertinoPageRoute(
// builder: (navigatorKey.currentState.context) => MessagesScreen(
// conversationId: data['conversation_id'],
// userId: data['user_id'],
// name: data['name'],
// avatar: data['avatar'],
// projectName: data['project_name'],
// projectId: data['project_id'],
// plus: data['plus'],
// ),
// ),
// );
}
}

Future<void> _firebaseMessagingBackgroundHandler(
RemoteMessage message) async {
print("onBackgroundMessage: $message");
}

enableIOSNotifications() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}

androidNotificationChannel() => const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
importance: Importance.max,
);
}

正如您在 onSelectNotification() 函数中看到的,我正在尝试导航但不知道如何导航。

我对 dart/flutter 很陌生,所以任何指导都将不胜感激。

最佳答案

你可以为你的导航设置一个全局键:

   final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

将其传递给 MaterialApp:

 new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: navigatorKey,
);

推送路由:

    navigatorKey.currentState.pushNamed('/someRoute');

关于flutter - 访问 BuildContext 以从推送通知服务 (Flutter) 导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71501027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com