본문으로 건너뛰기

เนื้อหาภาษาไทย / 태국어 콘텐츠

시스템 가이드 검수 완료된 콘텐츠

การใช้ Push Notifications ใน Flutter

บทความนี้อธิบายถึงการใช้งาน Push Notifications ใน Flutter โดยครอบคลุมทั้ง Firebase Cloud Messaging (FCM) สำหรับการส่ง notifications จาก server และ Local Notific...

การใช้ Push Notifications ใน Flutter

Push Notifications เป็นเครื่องมือสำคัญในการดึงดูดผู้ใช้กลับมายังแอปพลิเคชันของคุณ และแจ้งเตือนข้อมูลสำคัญต่างๆ ไม่ว่าจะเป็นข่าวสารล่าสุด, โปรโมชั่นพิเศษ, หรือการแจ้งเตือนเกี่ยวกับการดำเนินการบางอย่างในแอปพลิเคชัน ในบทความนี้ เราจะมาเรียนรู้วิธีการใช้งาน Push Notifications ใน Flutter โดยจะครอบคลุมถึง Firebase Cloud Messaging (FCM) สำหรับการส่ง notifications จาก server และ Local Notifications สำหรับการแจ้งเตือนที่เกิดขึ้นภายในแอปพลิเคชันเอง

ทำไมต้อง Push Notifications?

Push Notifications มีประโยชน์มากมาย ได้แก่:

  • Engagement: ช่วยให้ผู้ใช้กลับมาใช้งานแอปพลิเคชันของคุณอีกครั้ง
  • Real-time Updates: แจ้งเตือนข้อมูลใหม่ๆ ให้ผู้ใช้ทราบทันที
  • Personalization: ส่ง notifications ที่ปรับให้เหมาะสมกับผู้ใช้แต่ละราย
  • Marketing: โปรโมทสินค้าและบริการของคุณ
  • Critical Alerts: แจ้งเตือนเหตุการณ์สำคัญ เช่น การทำธุรกรรมสำเร็จ หรือข้อความใหม่

Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) เป็นบริการของ Google ที่ช่วยให้คุณส่ง Push Notifications ไปยังอุปกรณ์ Android, iOS และ Web ได้อย่างง่ายดาย เราจะมาดูขั้นตอนการใช้งาน FCM ใน Flutter:

1. การตั้งค่า Firebase Project

เริ่มต้นด้วยการสร้าง Firebase project บน Firebase Console (console.firebase.google.com) จากนั้นเพิ่มแอปพลิเคชัน Flutter ของคุณไปยัง project โดยทำตามขั้นตอนที่ Firebase Console แนะนำ ซึ่งรวมถึงการดาวน์โหลด google-services.json (สำหรับ Android) และ GoogleService-Info.plist (สำหรับ iOS) และเพิ่มไปยังโปรเจกต์ Flutter ของคุณ

2. การเพิ่ม Firebase dependencies ใน Flutter

เพิ่ม dependencies ที่จำเป็นในไฟล์ pubspec.yaml:

dependencies:
  firebase_core: ^2.0.0
  firebase_messaging: ^14.0.0

จากนั้นรัน flutter pub get เพื่อติดตั้ง dependencies

3. การ Initializing Firebase

ทำการ initialize Firebase ในแอปพลิเคชันของคุณ โดยปกติจะทำใน main() function:

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Push Notifications',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    requestPermission();
    getToken();
    initMessaging();
  }

  void requestPermission() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }
  }

  void getToken() async {
    String? token = await FirebaseMessaging.instance.getToken();
    print('Firebase Token: $token');
    // Send this token to your server to store it.  You will need this token to send push notifications to individual devices.
  }

  void initMessaging() {
    // Handle incoming messages when the app is in the foreground
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
        // Display a dialog or notification to the user.  This is a basic example, consider using a local notification plugin for more control.
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(message.notification!.title ?? 'Notification'),
              content: Text(message.notification!.body ?? 'No body'),
              actions: <Widget>[
                TextButton(
                  child: Text('Close'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    });

    // Handle when a notification is opened from terminated state
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        print("Opened from terminated state: ${message.notification?.title}");
        // Navigate to a specific screen based on the message data.
      }
    });

    // Handle when a notification is opened from background state
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      print('Message clicked!');
      // Navigate to a specific screen based on the message data.
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Push Notifications'),
      ),
      body: Center(
        child: Text('Check console for Firebase token and notifications'),
      ),
    );
  }
}

คำอธิบาย:

  • Firebase.initializeApp(): ทำการ initialize Firebase SDK
  • requestPermission(): ขอ permission จากผู้ใช้เพื่อรับ notifications
  • getToken(): ดึง FCM token ของอุปกรณ์
  • FirebaseMessaging.onMessage.listen(...): Handle notifications ที่เข้ามาเมื่อแอปพลิเคชันอยู่ใน foreground
  • FirebaseMessaging.instance.getInitialMessage().then(...): Handle notification ที่ถูกเปิดจาก terminated state (แอปปิดอยู่)
  • FirebaseMessaging.onMessageOpenedApp.listen(...): Handle notification ที่ถูกเปิดจาก background state (แอปทำงานอยู่เบื้องหลัง)

4. การส่ง Notifications จาก Server

เมื่อคุณมี FCM token แล้ว คุณสามารถใช้ token นี้เพื่อส่ง notifications ไปยังอุปกรณ์นั้นๆ ได้ คุณสามารถใช้ Firebase Console หรือ Firebase Admin SDK บน server ของคุณเพื่อส่ง notifications

ตัวอย่างการส่ง Notification ผ่าน Firebase Console:

  1. ไปที่ Firebase Console
  2. เลือก project ของคุณ
  3. ไปที่ "Cloud Messaging"
  4. คลิก "Send your first message"
  5. กรอกข้อมูล notification (Title, Text, Image)
  6. เลือก target (Single device โดยใช้ FCM token, Topic, หรือ User segment)
  7. ส่ง notification

ข้อควรระวัง:

  • ควรส่ง FCM Token ไปเก็บไว้ที่ Server เพื่อใช้ในการส่ง Push Notification
  • ควรจัดการ Error Handling อย่างเหมาะสมเมื่อขอ Permission หรือดึง Token
  • ควรพิจารณาการใช้ Topics หรือ User Segments เพื่อส่ง Notifications ที่เกี่ยวข้องไปยังกลุ่มเป้าหมายที่ถูกต้อง

Local Notifications

Local Notifications คือ notifications ที่ถูกสร้างขึ้นและแสดงผลภายในแอปพลิเคชันเอง โดยไม่ต้องพึ่งพา server ภายนอก เหมาะสำหรับแจ้งเตือนเหตุการณ์ที่เกิดขึ้นภายในแอป เช่น การแจ้งเตือนเมื่อครบกำหนดเวลา หรือการแจ้งเตือนเมื่อมีการเปลี่ยนแปลงสถานะ

1. การเพิ่ม Local Notifications dependency

เพิ่ม flutter_local_notifications dependency ในไฟล์ pubspec.yaml:

dependencies:
  flutter_local_notifications: ^16.0.0

จากนั้นรัน flutter pub get เพื่อติดตั้ง dependency

2. การ Initializing Local Notifications

ทำการ initialize FlutterLocalNotificationsPlugin:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('app_icon'); // replace 'app_icon' with the name of your app icon in the drawable folder

  final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
  );

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);

  runApp(MyApp());
}

3. การแสดง Local Notification

ใช้ flutterLocalNotificationsPlugin เพื่อแสดง local notification:

Future<void> showNotification() async {
  const AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
    'your channel id',
    'your channel name',
    channelDescription: 'your channel description',
    importance: Importance.max,
    priority: Priority.high,
    ticker: 'ticker',
  );
  const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails);
  await flutterLocalNotificationsPlugin.show(
      0, 'plain title', 'plain body', notificationDetails,
      payload: 'item x');
}

คำอธิบาย:

  • AndroidNotificationDetails: กำหนดรายละเอียดของ notification สำหรับ Android
  • NotificationDetails: รวมรายละเอียดของ notification สำหรับ platform ต่างๆ
  • flutterLocalNotificationsPlugin.show(...): แสดง notification

4. การจัดการ Notification Payload

คุณสามารถส่งข้อมูลเพิ่มเติม (payload) ไปพร้อมกับ notification เพื่อใช้ในการจัดการเมื่อผู้ใช้คลิกที่ notification

// ... (inside the initState of your StatefulWidget)
  flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onDidReceiveNotificationResponse: (NotificationResponse response) async {
    print('payload: ${response.payload}');
    // Handle the payload, e.g., navigate to a specific screen.
  });

ข้อควรระวัง:

  • ควรสร้าง Notification Channel สำหรับ Android 8.0 (API level 26) ขึ้นไป เพื่อให้ผู้ใช้สามารถควบคุมประเภทของ notifications ที่ต้องการรับได้
  • ควรจัดการ Error Handling อย่างเหมาะสมเมื่อแสดง Notification
  • ควรใช้ Payload เพื่อส่งข้อมูลที่จำเป็นสำหรับการนำทางหรือดำเนินการบางอย่างเมื่อผู้ใช้คลิก Notification

สรุป

Push Notifications เป็นเครื่องมือที่ทรงพลังในการเพิ่ม engagement และแจ้งเตือนข้อมูลสำคัญให้กับผู้ใช้ การใช้ FCM ช่วยให้คุณส่ง notifications ไปยังอุปกรณ์ต่างๆ ได้อย่างง่ายดาย ในขณะที่ Local Notifications ช่วยให้คุณสร้าง notifications ที่เกิดขึ้นภายในแอปพลิเคชันเอง การผสมผสานการใช้งานทั้งสองประเภทจะช่วยให้คุณสร้างประสบการณ์การใช้งานที่ดีให้กับผู้ใช้

Office.in.th Custom Service

이 구조를 바탕으로 시스템을 개발하거나 맞춤 변경하고 싶으신가요?

Office.in.th는 엔터프라이즈 웹 애플리케이션, API 연동, 공공/민간 업무 관리 시스템을 설계·개발하며 장기 지원을 제공합니다.

소프트웨어 개발 서비스 보기