惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
博客园_首页
美团技术团队
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
J
Java Code Geeks
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
雷峰网
雷峰网
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🔔 Flutter Push Notifications (Foreground, Background, Ter...
Codexlancers · 2026-06-02 · via DEV Community

Push notifications in Flutter look easy…
until you actually try to implement them.

Everything seems fine - until:

  • Notifications don't show in foreground
  • Background handlers never trigger
  • And terminated state? Completely broken.

If you've been there… yeah, same

We've faced all of this while working on a production app, and this guide is the exact setup that finally worked.

First - Understand Notification States (This is where most people go wrong)
Before writing a single line of code, you need to understand this:

Types of notifications

👉 Each state behaves differently. And if you treat them the same, things will break.

Basic Setup

1. Add dependencies

// pubspec.yaml

firebase_core: ^4.6.0
firebase_messaging: ^16.1.3
flutter_local_notifications: ^21.0.0

2. Initialize Firebase

Before using FCM, initialize Firebase when your app starts:

await Firebase.initializeApp();

3. Request Notification Permission

This step is mandatory on iOS and Android 13+.

FirebaseMessaging messaging = FirebaseMessaging.instance;

await messaging.requestPermission(
  alert: true,
  badge: true,
  sound: true,
);

Why is this important?

Starting from Android 13, Android requires explicit notification permission, similar to iOS.

If permission is not granted, notifications won't appear.

Android Notification Channel (Must for Android)

Without this, notifications may not show or may appear silently.

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel',
  'High Importance Notifications',
  description: 'This channel is used for important notifications.',
  importance: Importance.high,
);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
    ?.createNotificationChannel(channel);


iOS Foreground Notification Setup

iOS requires this to properly show notifications in foreground:

await FirebaseMessaging.instance
    .setForegroundNotificationPresentationOptions(
  alert: true,
  badge: true,
  sound: true,
);

👉 Without this, notifications may not appear even if everything else is correct.

Foreground Notifications (Most Common Confusion)

The problem

You send a notification and nothing shows when the app is open. 
Feels like it's broken, right?

The reality

FCM does NOT display notifications in foreground.

The fix

You must show it manually using local notifications:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  showLocalNotification(message);
});

💡 This is where most developers get stuck initially.

Background Notifications

This is where things start working automatically, but only if you do it right.

Works automatically IF your payload includes:

{
  "notification": {
    "title": "Hello",
    "body": "World"
  }
}

⚠️ Using data-only payload?

Then you MUST handle it manually:

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(); // Required in background isolate
  print("Handling background message");
}

👉 Also, this function must be top-level.
(Not inside a class - easy mistake.)

Terminated State (Most Confusing Part)

This is where most implementations fail.

The issue

User taps notification → app opens → but nothing happens.

The fix

Handle the initial message:

RemoteMessage? initialMessage =
    await FirebaseMessaging.instance.getInitialMessage();

if (initialMessage != null) {
  handleNotificationClick(initialMessage);
}

Also listen when app is opened from background:

FirebaseMessaging.onMessageOpenedApp.listen((message) {
  handleNotificationClick(message);
});

👉 Without this, deep linking or navigation won't work.

Navigation Tip

handleNotificationClick() should:

  • Read payload data
  • Navigate to a specific screen

Local Notification Setup (Required for Foreground)

Without this, your foreground notifications will never show.

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void showLocalNotification(RemoteMessage message) async {
  var androidDetails = AndroidNotificationDetails(
    'channel_id',
    'channel_name',
    importance: Importance.max,
    priority: Priority.high,
  );

  var generalNotificationDetails =
      NotificationDetails(android: androidDetails);

  await flutterLocalNotificationsPlugin.show(
    0,
    message.notification?.title,
    message.notification?.body,
    generalNotificationDetails,
  );
}

Common Mistakes (From Real Experience)

  • Not asking notification permission (Android 13+ especially)
  • Expecting foreground notifications to show automatically
  • Using only data payload and expecting UI
  • Background handler inside a class (won't work)
  • Forgetting getInitialMessage()

👉 We've personally hit almost all of these 😅

Final Thoughts

Push notifications in Flutter are not plug-and-play.
They require:

  • Proper setup
  • Understanding of app states
  • Correct payload structure

Key Takeaway

If your notifications are not working, 90% of the time:
👉 You didn't handle foreground manually
👉 OR your payload is wrong

If your notifications are not working on iOS or APNs token is not generating, check this:
👉 Flutter APNs Token Not Generating (Complete Fix Guide)

If this saved you hours of debugging, consider following for more Flutter deep dives.