Firebase Cloud Messaging и уведомления
Отправляйте и принимайте push-уведомления в приложении Flutter с помощью Firebase Cloud Messaging, обрабатывая состояния переднего плана, фона и нажатия.
«Firebase Cloud Messaging и уведомления» — бесплатный урок Flutter Mobile Development на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Flutter Mobile Development, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Flutter Mobile Development содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Push Notifications?
Firebase Cloud Messaging (FCM) lets your server send push notifications to users even when the app is closed. It is key for re-engagement and real-time alerts.
Adding the Package
Add firebase_messaging to your dependencies. You should already have firebase_core set up from earlier lessons.
dependencies:
firebase_core: ^2.0.0
firebase_messaging: ^14.0.0Requesting Permission
On iOS (and Android 13+) you must request notification permission from the user.
final messaging = FirebaseMessaging.instance;
await messaging.requestPermission(
alert: true, badge: true, sound: true,
);The Device Token
Each device gets a unique FCM token. Send it to your server so you can target that device.
final token = await messaging.getToken();
print('FCM token: ' + (token ?? 'none'));Token Refresh
Tokens can change. Listen for refreshes and update your server.
messaging.onTokenRefresh.listen((newToken) {
sendTokenToServer(newToken);
});Three Message States
You must handle messages in three situations:
- Foreground — app open
- Background — app minimized
- Terminated — app closed
Foreground Messages
When the app is open, FCM does not show a system notification automatically — you receive the data and display it yourself.
FirebaseMessaging.onMessage.listen((message) {
final title = message.notification?.title ?? '';
showLocalNotification(title);
});Background Handler
Register a top-level background handler before runApp. It must be a top-level function.
Future<void> bgHandler(RemoteMessage m) async {
print('Background: ' + (m.messageId ?? ''));
}
void main() {
FirebaseMessaging.onBackgroundMessage(bgHandler);
}Handling a Tapped Notification
When the user taps a notification that opened the app, route them to the right screen.
FirebaseMessaging.onMessageOpenedApp.listen((message) {
final route = message.data['route'];
if (route != null) navigator.pushNamed(route);
});Topic Subscriptions
Subscribe devices to topics to broadcast to groups without managing individual tokens.
await messaging.subscribeToTopic('news');
await messaging.unsubscribeFromTopic('news');Local Notifications for Display
Pair FCM with flutter_local_notifications to show rich notifications while in the foreground.
final plugin = FlutterLocalNotificationsPlugin();
await plugin.show(0, 'Title', 'Body', notificationDetails);Quick Check
What is true about a notification received while the app is in the foreground?
Recap
You learned Firebase Cloud Messaging:
- Permissions and device tokens
- Foreground, background and terminated handling
- Tapped-notification routing and topics
- Pairing with local notifications
Now your app can re-engage users with timely pushes.
Часто задаваемые вопросы
Урок «Firebase Cloud Messaging и уведомления» бесплатный?
Да — полный текст урока «Firebase Cloud Messaging и уведомления» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flutter Mobile Development, подпишись на CoddyKit PRO. Курс Flutter Mobile Development содержит 4 уроков всего.
Чему я научусь в уроке «Firebase Cloud Messaging и уведомления»?
Отправляйте и принимайте push-уведомления в приложении Flutter с помощью Firebase Cloud Messaging, обрабатывая состояния переднего плана, фона и нажатия. Ты практикуешь Flutter Mobile Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Flutter Mobile Development?
Предыдущий опыт не требуется. Flutter Mobile Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Firebase Cloud Messaging и уведомления»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Flutter Mobile Development?
Да. Каждый урок Flutter Mobile Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка Firebase и аутентификация
- Облачная база данных Firestore
- Облачное хранилище и функции
- Firebase Cloud Messaging и уведомления