如何在Flutter中按条件禁用推送通知?

aiazj4mn  于 2023-02-16  发布在  Flutter
关注(0)|答案(1)|浏览(190)

我有一个应用程序,我想只向授权用户发送通知,如果令牌为空,则用户未被授权,令牌授权和存储我使用shared_pref包。如果用户未登录,如何禁用通知?令牌验证仅在MyAppState通知中完成我需要在同一位置禁用

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  await Permission.notification.request();

  if(Constants.USER_TOKEN.isEmpty) {
    FirebaseMessaging.instance.setAutoInitEnabled(false);
  }
  RemoteMessage? initialMessage =
      await FirebaseMessaging.instance.getInitialMessage();
  if (initialMessage != null) {
    if (navKey.currentState != null) {
      if(Constants.USER_TOKEN.isNotEmpty) {
        navKey.currentState!.push(MaterialPageRoute(
            builder: (context) => NotificationScreen()));
      }
      print('Message');
    }
  }
  await _messaging.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,
            channelDescription: channel.description,
            icon: '@mipmap/ic_launcher',
          ),
        ),
      );
    }
  });
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage? message) {
    print("On message opened app: ${message?.data}}");
    if (navKey.currentState != null) {
      if(Constants.USER_TOKEN.isNotEmpty) {
        navKey.currentState!.push(MaterialPageRoute(
            builder: (context) => const NotificationScreen()));
      }
    }
  });

  var initializationSettingsAndroid =
      const AndroidInitializationSettings('@drawable/ic_notification');

  var initializationSettingsIOS = const DarwinInitializationSettings();

  var initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
  await _messaging.requestPermission();
  String? token = await _messaging.getToken();
  if (token != null) {
    print("FIREBASE TOKEN $token");
  } else {
    print("CANNOT TAKE FIREBASE TOKEN");
  }
  if (Platform.isIOS) {
    var APNS = await _messaging.getAPNSToken();
    print('APNS: $APNS');
  }
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  getToken() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      Constants.USER_TOKEN = pref.getString('login') ?? "";
    });
  }

  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
    await getToken();
  }
unguejic

unguejic1#

启用时,使用deleteToken使当前令牌无效,并再次使用getToken获取新令牌。

getToken() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    setState(() {
      Constants.USER_TOKEN = pref.getString('login') ?? "";
    });

if(Constants.USER_TOKEN.isEmpty()){

    // delete firebase token

}else{

    // get firebase token

}
     }

相关问题