شرح كيفية ارسال اشعارات من الفايربيز الى التطبيق في flutter

شرح كيفية ارسال اشعارات من الفايربيز الى التطبيق في flutter

شرح كيفية ارسال اشعارات من الفايربيز الى التطبيق في flutter

في هذا المقال سوف نشرح لكم كيف تتم عملية ارسال الاشعارات من الfirebase الى التطبيق الخاص بك بكل سهوله والامر بسيط جدا وسوف يتم تغطيته في هذه المقاله ولتنفيذ هذه العمليه سوف نحتاج الى تثبيت المكتبة الخاصه بالفايربيز والمسؤوله عن عملية الارسال والاشعارات وبعدها سوف نحتاج مكتبة اخرى لكي نعرض بها الاشعار وكلا المكتبتين سوف تجدون طريقة التثبيت الخاصه بهم في الجزء التالي كل ما عليك هو نسخ الاكواد ولصقها في المكان المطلوب لكي تتم معك عملية الارسال بشكل صحيح بدون اي مشاكل .


Flutter هو تطبيق SDK للجوّال يسمح بإنشاء رمز متزامن لنظامي التشغيل iOS و Android. تطبيقين بأداء رائع ودقة. Flutter الهدف هو إعطاء المطورين الأدوات التي يحتاجونها لإنشاء برامج عالية الأداء تعمل بسلاسة عبر العديد من الأنظمة الأساسية. يمكننا استيعاب العديد من اختلافات الأيقونات ومشكلات التنضيد وسلوك التمرير. لبدء الاستخدام ، لا تحتاج إلى أي معرفة سابقة بتطوير الأجهزة المحمولة. إذا كنت قد استخدمت لغة Java أو JavaScript ، فسيبدو التطبيق مألوفًا لك لأنه تمت كتابته بلغة برمجة Dart. على الرغم من أن الكتابة بلغات شيئية تعد ميزة إضافية ، إلا أن بعض تطبيقات Flutter قد تم إنشاؤها من قبل غير المبرمجين!


add two package


  flutter_local_notifications: ^9.4.0

  firebase_messaging: ^11.2.8


how to use firebase with notifications


ما سوف نقوم به اولا سوف نحتاج الحصول على الtoken الخاص بالمستخدم لكي نستطيع ارسال اشعار له ويمكنك القيام بذلك عن طريق استخدام المكتبة وسوف تجد خيار يسمح لك بالحصول على التوكن الخاص بالمستخدم ويقوم بطباعته وبعدها انسخ هذا التوكن وسوف نحتاجه في الخطوة التاليه والتي سوف نرسل من خلالها الاشعار , الان نستخدم الامر onMessage وهنا يعبر عند وصول اي حدث للتطبيق وما سوف نقوم به اننا سوف نعرض اشعار عندما يحدث عملية ارسال من الفايربيز الى الميثود المسؤوله عن ذلك بعدها نرسل لها الاشعار , وبعدها استخدمنا الامر payload وهذا يعبر عن الضغط على الاشعار وبعد الضغط على الاشعار سوف نقوم بنقله الى صفحة التي يوجد بها المستخدمين الذين يستعملون التطبيق ايضا بداخل الchannel سوف يكون معبر عن ظهور الاشعار وسوف نرسل له البيانات التي نريد عرضها للمستخدم ونعرضها بداخل الchannel وبهذا نعرض العنوان والنص .


how to use firebase with notifications

main.dart


class MyApp extends StatefulWidget {
  const MyApp({Key? key, required this.startWidget}) : super(key: key);
  final Widget startWidget;

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

class _MyAppState extends State<MyApp> {
  final navigatorKey = GlobalKey<NavigatorState>();
  @override
  void initState() {
    super.initState();
    // print token .
    FirebaseMessaging.instance
        .getToken()
        .then((value) => print('token is $value'));

    FirebaseMessaging.onMessage.listen((event) {
      print('test notification is ----- ${event.data}');
      print('test notification is ----- ${event.notification!.title}');
      print('test notification is ----- ${event.notification!.body}');
      showNotification(event.notification!);
    });
  }

  void showNotification(RemoteNotification notification) async {
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
    // initialise the plugin.
    // app_icon needs to be a added as a
    // drawable resource to the Android head project
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');


    /// define platforms .
    // final IOSInitializationSettings initializationSettingsIOS =
    //     IOSInitializationSettings(
    //         onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    //
    // final MacOSInitializationSettings initializationSettingsMacOS =
    //     MacOSInitializationSettings();


    /// Initialization platforms
    const InitializationSettings initializationSettings =
    InitializationSettings(
      android: initializationSettingsAndroid,
      // iOS: initializationSettingsIOS,
      // macOS: initializationSettingsMacOS
    );

    // select notification | payload = data from FirebaseMessaging
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (payload) => selectNotification(payload!),);

    // channels notification .
    channelNotification(flutterLocalNotificationsPlugin,notification);

  }

  void selectNotification(String payload) {
    navigatorKey.currentState!.pushReplacement(MaterialPageRoute(
      builder: (context) => const AllUserChattingPage(),
    ),);
    // navigateAndFinish(context, const AllUserChattingPage());
  }

  void channelNotification(FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin ,
      RemoteNotification notification) async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails('your channel id', 'your channel name',
        channelDescription: 'your channel description',
        // Importance
        importance: Importance.max,
        // Priority
        priority: Priority.high,
        ticker: 'ticker');
    const NotificationDetails platformChannelSpecifics =
    NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(

      // 1- number of notification => notification.hashCode = Not a specific number
      // 0 = one message only .

      // 2- title of message
      // 3- body of message

        notification.hashCode,
      	notification.title,
      	notification.body,
      	platformChannelSpecifics,
        payload: 'item x');}

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => LoginBloc(),
        ),
        BlocProvider(
          create: (context) => RegisterBloc(),
        ),
        BlocProvider(
          create: (context) => AddPostCubit(),
        ),
        BlocProvider(
          create: (context) => HomeBlocCubit(),
        ),
        BlocProvider(
          create: (context) => CommentCubit(),
        ),
        BlocProvider(
          create: (context) => ChatBloc(),
        ),
      ],
      child: MaterialApp(
        useInheritedMediaQuery: true,
        debugShowCheckedModeBanner: false,
        navigatorKey: navigatorKey,
        title: 'Flutter Demo',
        theme: ThemeData(
          scaffoldBackgroundColor: Colors.black12,
          appBarTheme: const AppBarTheme(
            backgroundColor: Colors.black12,
          ),
          focusColor: Colors.white,
          textTheme: const TextTheme(
              bodyText1: TextStyle(
            color: Colors.white,
            fontSize: 16,
          )),
          primarySwatch: Colors.blue,
        ),
        home: widget.startWidget,
      ),
    );
  }


}


how to send message from cloud messaging


بعد طباعة التوكن انتقل الى حسابك في الفايربيز وبعدها الى cloud messaging وهنا سوف نقوم بعمل اختبار للاشعارات سوف تضع نص وعنوان للنص وبعدها تضغط على الامر test message وهنا تضع التوكن الخاص بالمستخدم الذي تريد ان ترسل له الاشعار وبهذا سوف يصل اشعار للمستخدم بكل بساطة .


how to send message from cloud messaging

مزيد من المقالات

تعليقات