0Pricing
Flutter Mobile Development · Aula

Firebase Cloud Messaging e Notificações

Envie e receba notificações push no seu aplicativo Flutter usando o Firebase Cloud Messaging, lidando com estados em primeiro plano, segundo plano e após o toque.

Firebase Cloud Messaging e Notificações é uma aula grátis de Flutter Mobile Development no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Flutter Mobile Development, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Flutter Mobile Development inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.0

Requesting 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.

Perguntas Frequentes

A aula “Firebase Cloud Messaging e Notificações” é grátis?

Sim — o texto completo de “Firebase Cloud Messaging e Notificações” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Flutter Mobile Development, atualize para CoddyKit PRO. O curso de Flutter Mobile Development inclui 4 aulas no total.

O que vou aprender em “Firebase Cloud Messaging e Notificações”?

Envie e receba notificações push no seu aplicativo Flutter usando o Firebase Cloud Messaging, lidando com estados em primeiro plano, segundo plano e após o toque. Você pratica Flutter Mobile Development com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Flutter Mobile Development?

Nenhuma experiência prévia é necessária. Flutter Mobile Development no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Firebase Cloud Messaging e Notificações”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Flutter Mobile Development?

Sim. Cada aula de Flutter Mobile Development inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Configuração e autenticação do Firebase
  2. Banco de dados Cloud Firestore
  3. Armazenamento e funções na nuvem
  4. Firebase Cloud Messaging e Notificações
← Voltar para Flutter Mobile Development