Note: Setup Flutter, FlutterFire, and Firebase Cloud Messaging with awesome notifications
สร้าง Firebase Project
เริ่มจากให้ตั้งชื่อ Package Name ของ android และ Bundle ID ของ IOS เอาไว้ก่อนตัวอย่างเช่น com.orgname.appname
เสร็จแล้วให้เข้าไปสร้าง project ใน https://console.firebase.google.com/ และ setup setup step 1 กำหนด Package Name ของ android และ Bundle ID ของ IOS ให้เรียบร้อย


เมื่อสร้าง project และ setup step 1 เรียบร้อยแล้ว
setup step 2 ให้ downaload file "google-services.json" และ "GoogleService-Info.plist" มา
สำหรับ Android ให้เอาไปไว้ที่ root-path/android/app

สำหรับ IOS ให้เอาไฟล์ GoogleService-Info.plist ไปไว้ที่ root-part/Runner/GoogleService-Info.plist
ตัวอย่างตามภาพนี้

ติดตั้ง FlutterFire และ FlutterFire Cli
ให้ติดตั้ง FlutterFire เพื่อใช้ในการจัดการ connect Flutter application เข้ากับ Firebase
การ install plugin ให้รัน command ตามนี้ใน root project path:
flutter pub add firebase_core
จากนั้นให้ install FlutterFire CLI (recommended)
# Install the CLI if not already done so
dart pub global activate flutterfire_cli
# Run the `configure` command, select a Firebase project and platforms
flutterfire configure

ถ้าไม่มีอะไรผิดพลาดจะได้ผลลัพตามภาพด้านบนนี้
ในส่วนนี้จำเป็นต้องติดตั้ง firebase cli ให้เรียบร้อย และ firebase login --reauth ก่อน อ่านเพิ่มเติมเกี่ยวกับ firebase cli
ในกรณีที่มี Error: FormatException: Unexpected character when calling flutterfire configure ดูวิธีแก้ได้ที่นี้ 🛠
จากนั้นเมื่อรัน flutterfire configure เสร็จแล้ว flutterfire จะสร้างไฟล์ firebase_options.dart ขึ้นมาโดนที่ข้างในนี้จะมี Default Firebase Options ทั้งหมดที่จำเป็นในการใช้งาน
ต่อไปให้เข้าไประบุ initializeApp
method เนื่องจากส่วนี้เป็น asynchronous operation ที่ main
function จะต้องแก้ให้ในแบบที่ ต้องแน่ใจว่าในตอนที่ initialization จะต้องเสร็จก่อนจะมีการเรียกใช้งาน application
เริ่มจาก import firebase_core
plugin และ firebase_options.dart
ไฟล์ที่ถูกสร้างขึ้น:
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
ต่อไปใน main
function ต้องมั่นใจว่า WidgetsFlutterBinding ถูก initialized รวมไปถึง initialize Firebase ด้วย
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}
DefaultFirebaseOptions.currentPlatform
จะถูก imported มาจาก firebase_options.dart ไฟล์
ถ้าหากต้องการ Manual Installation ส่วนนี้ สาารรถเข้าไปดูรายละเอียดได้ ที่นี่ แต่การ Manual Installation ไม่ใช่ขั้นตอนการติดตั้งที่แนะนำ
การ setup Firebase Cloud Messaging
ขั้นตอนแรกให้ Add dependency โดยใช้คำสั่งนี้
flutter pub add firebase_messaging
flutter pub add awesome_notification
จากนั้นให้ไปเพิ่ม dependencies ที่ไฟล์ pubspec.yaml
firebase_core: ^1.11.0
firebase_messaging: ^11.2.5
awesome_notifications: any
ตามในภาพ

ต้องการข้อมูลเพิ่มเติมสำหรับ awesome_notifications ไปดูต่อที่ https://pub.dev/packages/awesome_notifications
จากนั้นไปเพิ่ม classpath สำหรับ google-services ที่ android/build.gradle
classpath 'com.google.gms:google-services:4.3.10'
ตามภาพนี้

และเพิ่มบรรทัดด้านล่างนี้ที่ android/app/build.gradle ด้วย
apply plugin: 'com.google.gms.google-services'

ต่อไปจะเป็นส่วนของการ Coding โดยให้เข้าไปแก้ไขที่ไฟล์ lib/main.dart
// import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
AwesomeNotifications().initialize('resource://drawable/notification_icon', [
// notification icon
NotificationChannel(
channelGroupKey: 'basic_test',
channelKey: 'basic',
channelName: 'Basic notifications',
channelDescription: 'Notification channel for basic tests',
channelShowBadge: true,
importance: NotificationImportance.High,
),
//add more notification type with different configuration
]);
//click listiner on local notification
AwesomeNotifications()
.actionStream
.listen((ReceivedNotification receivedNotification) {
debugPrint("ReceivedNotification");
debugPrint(receivedNotification.payload!['title']);
//output from local notification click.
});
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.instance
.subscribeToTopic("all"); //subscribe firebase message on topic
FirebaseMessaging.onBackgroundMessage(firebaseBackgroundMessage);
//background message listiner
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
// Declared as global, outside of any class
Future<void> firebaseBackgroundMessage(RemoteMessage message) async {
print("-- firebaseBackgroundMessage");
AwesomeNotifications().createNotification(
content: NotificationContent(
//with image from URL
id: 1,
channelKey: 'basic', //channel configuration key
title: message.data["title"],
body: message.data["body"],
displayOnForeground: true,
// icon: message.data["icon"],
// bigPicture: message.data["image"],
// notificationLayout: NotificationLayout.BigPicture,
payload: {"name": "flutter"}));
print('Handling a background message ${message.messageId}');
}
Future<void> onFirebaseLaunchApp(RemoteMessage message) async {
print("-- onFirebaseLaunchApp: $message");
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// FirebaseMessaging messaging = FirebaseMessaging.instance;
int _counter = 0;
@override
void initState() {
FirebaseMessaging.onMessage.listen(firebaseBackgroundMessage);
// FirebaseMessaging.onMessageOpenedApp.listen(onFirebaseLaunchApp);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
_incrementCounter();
var view = message.data["view"];
print("-- onMessageOpenedApp: $view");
});
//active app listiner.
super.initState();
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Video Tutorial สำหรับ AwesomeNotifications
มันช่าง Awesome จริงๆ
github: https://github.com/rafaelsetragni/awesome_notifications
การใช้ pyfcm ส่ง notification ไปที่ client
Doc: https://pypi.org/project/pyfcm/
ติดตั้ง
pip install pyfcm
การใช้งาน
# Send to single device.
from pyfcm import FCMNotification
from datetime import datetime
API_KEY="put-api-key-here"
push_service = FCMNotification(api_key=API_KEY)
# Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
time_now = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
registration_id = "<device registration_id>"
message_title = f"ทดสอบ at {time_now}"
message_body = "สวัสดีจอห์นชาวไร ข่าวที่คุณกำหนด สำหรับวันนี้พร้อมแล้ว"
click_action="",
message_icon="notification_icon"
message_image = 'https://www.fluttercampus.com/img/uploads/web/2021/02/c4ca4238a0b923820dcc509a6f75849b.webp'
# result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
extra_notification_kwargs = {
'image': message_image,
'channelKey': "basic",
}
data_message = {
'view': 'PAGE_LOCATION_ACTIVITY'
}
# Send a message to devices subscribed to a topic.
result = push_service.notify_topic_subscribers(
topic_name="all",
message_title=message_title,
message_body=message_body,
extra_notification_kwargs=extra_notification_kwargs,
data_message=data_message,
message_icon=message_icon)
print(result)
จากใน code จะเห็นว่า จะต้องใช้ firebase api-key เพื่อเชื่อมต่อเข้ากับ firebase สามรถเข้าไปหาได้จาก https://console.firebase.google.com/project/settings/cloudmessaging หรือเมนู project overview-> Project settings คลิกที่ tab cloud messaging

จากนั้นจะเข้ามาที่หน้านี้

ส่วนที่เราต้องการคือ server key ให้เอาไปใส่ที่ api-key
การใช้งาน
python send.py
# result ที่ได้
{'multicast_ids': [], 'success': 1, 'failure': 0, 'canonical_ids': 0, 'results': [], 'topic_message_id': 6615027343234135558}
ถ้าไม่มีอะไรผิดพลาดเมื่อรัน send.py จะได้ผลลัพประมาณนี้ที่ futter app

เมื่อคลิกที่ notificaion ใน emu
