ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Flutter) Anroid,iOS에서 FCM 메세지 구현하기
    Programing Language/Flutter(Dart) 2022. 2. 17. 20:00
    728x90
    반응형

    안드로이드, iOS 기본 세팅 참고 url

    https://velog.io/@leedool3003/Flutter-FCM-Firebase-Cloud-Messagin-%EC%97%B0%EB%8F%99

     

    [Flutter] FCM, Firebase Cloud Messagin 연동

    FCM 을 이용하여 Flutter 알림을 만들어보자.

    velog.io

     

    pubspec.yaml

    firebase_messaging: ^11.1.0
      
    firebase_core: ^1.10.0
    
    flutter_local_notifications: ^9.3.2

     

    main.dart의 void() 함수에 (안드로이드에서 반드시 firebaseOptions을 꼭 적어줘야합니다!)

    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      print('Handling a background message ${message.messageId}');
    }
    
    late AndroidNotificationChannel channel;
    late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
    
    void main() async {
      /** 
       * Flutter는 main 메소드를 앱의 시작점으로 사용합니다. main 메소드에서 서버나 SharedPreferences 등 비동기로 데이터를 다룬 다음 runApp을 실행해야하는 경우 아래 한줄을 반드시 추가해야합니다.
       */
      WidgetsFlutterBinding.ensureInitialized();
      if (Platform.isIOS) {
        await Firebase.initializeApp();
      } else {
        //안드로이드에서는 반드시 FirebaseOptions을 추가해줘야한다.
        await Firebase.initializeApp(
            options: const FirebaseOptions(
                apiKey: '', // google-service.json 파일에 값 확인가능
                appId: '',// 나머지 세개는 firebase console 페이지에서 확인가능
                messagingSenderId: '',
                projectId: ''));
      }
    
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    
      channel = const AndroidNotificationChannel(
        'funidea_fcm_channel_id', // id
        'High Importance Notifications', // title
        description:
            'This channel is used for important notifications.', // description
        importance: Importance.high,
      );
    
      var initialzationSettingsAndroid =
          AndroidInitializationSettings('@mipmap/ic_launcher');
    
      var initialzationSettingsIOS = IOSInitializationSettings(
        requestSoundPermission: true,
        requestBadgePermission: true,
        requestAlertPermission: true,
      );
    
      flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);
    
      var initializationSettings = InitializationSettings(
          android: initialzationSettingsAndroid, iOS: initialzationSettingsIOS);
    
      await flutterLocalNotificationsPlugin.initialize(
        initializationSettings,
      );
    
      await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
      );
    
      String? token = await FirebaseMessaging.instance.getToken();
    
      print("token : ${token ?? 'token NULL!'}");
    
      runApp(const App());
    }
    
    class App extends StatefulWidget {
      const App({Key? key}) : super(key: key);
    
      @override
      State<App> createState() => _WebViewAppState();
    }
    
    class _WebViewAppState extends State<App> {
      static const baseUrl = "https://naver.com"; //실행시킬 url 작성
      // static const baseUrl = "http://172.30.1.8:8080"; //실행시킬 url 작성
    
      @override
      void initState() {
        if (Platform.isAndroid) {
          WebView.platform = SurfaceAndroidWebView();
        }
    
        FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;
          var androidNotiDetails = AndroidNotificationDetails(
            channel.id,
            channel.name,
            channelDescription: channel.description,
          );
          var iOSNotiDetails = const IOSNotificationDetails();
          var details =
              NotificationDetails(android: androidNotiDetails, iOS: iOSNotiDetails);
          if (notification != null) {
            flutterLocalNotificationsPlugin.show(
              notification.hashCode,
              notification.title,
              notification.body,
              details,
            );
          }
        });
    
        FirebaseMessaging.onMessageOpenedApp.listen((message) {
          print(message);
        });
    
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              appBarTheme: const AppBarTheme(
                  color: Colors.white,
                  shadowColor: Colors.transparent,
                  centerTitle: false),
              scaffoldBackgroundColor: Colors.white,
              primaryColor: const Color.fromRGBO(40, 150, 255, 1),
            ),
            home: SafeArea(
              child: container() //첫 화면이 시작되는 widge을 넣으세요.
              ),
            ));
      }
    }

     

    도움 되셨다면 하단의 광고 클릭 부탁드립니다:)

    728x90
    반응형
Designed by Tistory.