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

推荐订阅源

K
Kaspersky official blog
T
Threat Research - Cisco Blogs
N
News and Events Feed by Topic
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 叶小钗
Security Latest
Security Latest
Spread Privacy
Spread Privacy
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
U
Unit 42
Cyberwarzone
Cyberwarzone
小众软件
小众软件
Scott Helme
Scott Helme
Engineering at Meta
Engineering at Meta
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
爱范儿
爱范儿
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Latest news
Latest news
GbyAI
GbyAI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
PCI Perspectives
PCI Perspectives
Jina AI
Jina AI
AI
AI
NISL@THU
NISL@THU
I
Intezer
G
GRAHAM CLULEY
B
Blog
S
Secure Thoughts
IT之家
IT之家
宝玉的分享
宝玉的分享
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
V2EX - 技术
V2EX - 技术
Recorded Future
Recorded Future
Hacker News - Newest:
Hacker News - Newest: "LLM"

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Supabase Realtime with Flutter — Postgres Changes, Presence, and Broadcast in Practice
kanta13jp1 · 2026-05-03 · via DEV Community

Supabase Realtime streams PostgreSQL changes to clients over WebSocket. Combine it with Flutter and you can ship live notifications, "who's online" indicators, and collaborative editing in dozens of lines of code. This guide covers all three channel types — Postgres Changes, Presence, and Broadcast — with production-ready examples.

The Three Channel Types

Type Use Case Data Source
Postgres Changes React to INSERT/UPDATE/DELETE PostgreSQL WAL
Broadcast Client-to-client events Realtime server
Presence "Who's online" state sync Realtime server

Setup

# pubspec.yaml
dependencies:
  supabase_flutter: ^2.5.0

Enter fullscreen mode Exit fullscreen mode

// main.dart
import 'package:supabase_flutter/supabase_flutter.dart';

void main() async {
  await Supabase.initialize(
    url: 'https://<project>.supabase.co',
    anonKey: '<anon-key>',
    realtimeClientOptions: const RealtimeClientOptions(
      eventsPerSecond: 10,
      logLevel: RealtimeLogLevel.info,
    ),
  );
  runApp(const App());
}

final supabase = Supabase.instance.client;

Enter fullscreen mode Exit fullscreen mode

1. Postgres Changes — Real-time DB Events

Enable Realtime on Your Table

-- Run in Supabase Dashboard or a migration file
ALTER TABLE notifications REPLICA IDENTITY FULL;
ALTER PUBLICATION supabase_realtime ADD TABLE notifications;

-- RLS: users see only their own notifications
CREATE POLICY "users can view own notifications"
  ON notifications FOR SELECT
  USING (user_id = auth.uid());

Enter fullscreen mode Exit fullscreen mode

Subscribe in Flutter

class NotificationService {
  RealtimeChannel? _channel;

  void subscribe(String userId, void Function(Map<String, dynamic>) onNew) {
    _channel = supabase
        .channel('notifications:$userId')
        .onPostgresChanges(
          event: PostgresChangeEvent.insert,
          schema: 'public',
          table: 'notifications',
          filter: PostgresChangeFilter(
            type: PostgresChangeFilterType.eq,
            column: 'user_id',
            value: userId,
          ),
          callback: (payload) => onNew(payload.newRecord),
        )
        .onPostgresChanges(
          event: PostgresChangeEvent.update,
          schema: 'public',
          table: 'notifications',
          filter: PostgresChangeFilter(
            type: PostgresChangeFilterType.eq,
            column: 'user_id',
            value: userId,
          ),
          callback: (payload) {
            // Handle read-status updates
            debugPrint('Updated: ${payload.newRecord}');
          },
        )
        .subscribe();
  }

  void unsubscribe() {
    _channel?.unsubscribe();
    _channel = null;
  }
}

Enter fullscreen mode Exit fullscreen mode

Notification Bell Widget

class NotificationBell extends StatefulWidget {
  const NotificationBell({super.key});

  @override
  State<NotificationBell> createState() => _NotificationBellState();
}

class _NotificationBellState extends State<NotificationBell> {
  final _service = NotificationService();
  int _unreadCount = 0;
  final _items = <Map<String, dynamic>>[];

  @override
  void initState() {
    super.initState();
    _loadInitial();
    _service.subscribe(supabase.auth.currentUser!.id, _onNew);
  }

  Future<void> _loadInitial() async {
    final data = await supabase
        .from('notifications')
        .select()
        .eq('user_id', supabase.auth.currentUser!.id)
        .eq('read', false)
        .order('created_at', ascending: false)
        .limit(20);

    if (!mounted) return;
    setState(() {
      _items.addAll(List<Map<String, dynamic>>.from(data));
      _unreadCount = _items.length;
    });
  }

  void _onNew(Map<String, dynamic> notification) {
    setState(() {
      _items.insert(0, notification);
      _unreadCount++;
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(notification['message'] as String? ?? 'New notification')),
    );
  }

  @override
  void dispose() {
    _service.unsubscribe();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Badge(
      isLabelVisible: _unreadCount > 0,
      label: Text('$_unreadCount'),
      child: IconButton(
        icon: const Icon(Icons.notifications_outlined),
        onPressed: () => showModalBottomSheet(
          context: context,
          builder: (_) => _NotificationPanel(items: _items),
        ),
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

2. Presence — Track Who's Online

Presence syncs each client's arbitrary state object (online status, cursor position, active document…) to every subscriber in the channel.

class PresenceService {
  RealtimeChannel? _channel;
  final _users = <String, Map<String, dynamic>>{};

  void Function(Map<String, Map<String, dynamic>>)? onSync;

  void join({
    required String roomId,
    required String userId,
    required String displayName,
    String? avatarUrl,
  }) {
    _channel = supabase.channel('room:$roomId')
      ..onPresenceSync((_) {
        _users.clear();
        _channel!.presenceState().forEach((_, presences) {
          if (presences.isNotEmpty) {
            final p = presences.first;
            _users[p['user_id'] as String] = Map<String, dynamic>.from(p);
          }
        });
        onSync?.call(Map.unmodifiable(_users));
      })
      ..onPresenceJoin((payload) {
        for (final p in payload.newPresences) {
          debugPrint('${p['display_name']} joined');
        }
      })
      ..onPresenceLeave((payload) {
        for (final p in payload.leftPresences) {
          _users.remove(p['user_id']);
        }
        onSync?.call(Map.unmodifiable(_users));
      });

    _channel!.subscribe((status, _) async {
      if (status == RealtimeSubscribeStatus.subscribed) {
        await _channel!.track({
          'user_id': userId,
          'display_name': displayName,
          'avatar_url': avatarUrl,
          'online_at': DateTime.now().toIso8601String(),
        });
      }
    });
  }

  /// Update cursor position for live collaboration
  Future<void> updateCursor(double x, double y) async {
    await _channel?.track({'cursor': {'x': x, 'y': y}});
  }

  Future<void> leave() async {
    await _channel?.untrack();
    await _channel?.unsubscribe();
    _channel = null;
  }
}

Enter fullscreen mode Exit fullscreen mode

Online Users Avatars Widget

class OnlineAvatarRow extends StatelessWidget {
  final Map<String, Map<String, dynamic>> users;
  final int maxVisible;

  const OnlineAvatarRow({
    super.key,
    required this.users,
    this.maxVisible = 5,
  });

  @override
  Widget build(BuildContext context) {
    final list = users.values.toList();
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        ...list.take(maxVisible).map((u) {
          final name = u['display_name'] as String? ?? '?';
          final avatar = u['avatar_url'] as String?;
          return Padding(
            padding: const EdgeInsets.only(right: 4),
            child: Tooltip(
              message: name,
              child: CircleAvatar(
                radius: 14,
                backgroundImage: avatar != null ? NetworkImage(avatar) : null,
                child: avatar == null ? Text(name[0].toUpperCase()) : null,
              ),
            ),
          );
        }),
        if (list.length > maxVisible)
          Text(
            '+${list.length - maxVisible}',
            style: Theme.of(context).textTheme.labelSmall,
          ),
        const SizedBox(width: 6),
        Row(children: [
          Container(
            width: 8,
            height: 8,
            decoration: const BoxDecoration(
              color: Colors.green,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 4),
          Text('${list.length} online',
              style: Theme.of(context).textTheme.labelSmall),
        ]),
      ],
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

3. Broadcast — Low-latency Peer Messaging

Broadcast skips the database entirely — perfect for chat messages, emoji reactions, and live cursors.

class ChatBroadcastService {
  RealtimeChannel? _channel;

  void Function(ChatMessage)? onMessage;
  void Function(String userId, String emoji)? onReaction;

  void connect(String roomId) {
    _channel = supabase.channel(
      'chat:$roomId',
      opts: const RealtimeChannelConfig(ack: false),
    )
      ..onBroadcast(
        event: 'message',
        callback: (payload) => onMessage?.call(ChatMessage.fromJson(payload)),
      )
      ..onBroadcast(
        event: 'reaction',
        callback: (payload) => onReaction?.call(
          payload['user_id'] as String,
          payload['emoji'] as String,
        ),
      )
      ..subscribe();
  }

  Future<void> sendMessage(ChatMessage msg) => _channel!.sendBroadcastMessage(
        event: 'message',
        payload: msg.toJson(),
      );

  Future<void> react(String userId, String emoji) =>
      _channel!.sendBroadcastMessage(
        event: 'reaction',
        payload: {'user_id': userId, 'emoji': emoji},
      );

  void disconnect() {
    _channel?.unsubscribe();
    _channel = null;
  }
}

class ChatMessage {
  final String id;
  final String userId;
  final String displayName;
  final String body;
  final DateTime sentAt;

  const ChatMessage({
    required this.id,
    required this.userId,
    required this.displayName,
    required this.body,
    required this.sentAt,
  });

  factory ChatMessage.fromJson(Map<String, dynamic> j) => ChatMessage(
        id: j['id'] as String,
        userId: j['user_id'] as String,
        displayName: j['display_name'] as String,
        body: j['body'] as String,
        sentAt: DateTime.parse(j['sent_at'] as String),
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'user_id': userId,
        'display_name': displayName,
        'body': body,
        'sent_at': sentAt.toIso8601String(),
      };
}

Enter fullscreen mode Exit fullscreen mode

4. Rate Limits and Throttling

/// Throttle broadcasts to avoid hitting plan limits.
class ThrottledChannel {
  final RealtimeChannel _channel;
  final Duration _interval;
  Timer? _timer;
  Map<String, dynamic>? _pending;

  ThrottledChannel(this._channel, {Duration interval = const Duration(milliseconds: 50)})
      : _interval = interval;

  void send(String event, Map<String, dynamic> payload) {
    _pending = {'event': event, 'payload': payload};
    _timer ??= Timer(_interval, _flush);
  }

  void _flush() {
    if (_pending != null) {
      _channel.sendBroadcastMessage(
        event: _pending!['event'] as String,
        payload: _pending!['payload'] as Map<String, dynamic>,
      );
      _pending = null;
    }
    _timer = null;
  }

  void dispose() => _timer?.cancel();
}

// 30fps cursor broadcast
final _cursorChannel = ThrottledChannel(
  channel,
  interval: const Duration(milliseconds: 33),
);

void onPointerMove(PointerMoveEvent event) {
  _cursorChannel.send('cursor', {'x': event.position.dx, 'y': event.position.dy});
}

Enter fullscreen mode Exit fullscreen mode

Plan Limits (as of 2030)

Plan Connections Messages/sec Presence members
Free 200 10 100/channel
Pro 500 100 500/channel
Team 10,000 500 10,000/channel

Summary

The three Realtime channel types cover distinct needs:

  • Postgres Changes — database-driven notifications with RLS security
  • Presence — synchronized online state across all clients
  • Broadcast — low-latency peer events without a database round-trip

Combined with Flutter's reactive UI model, Supabase Realtime lets a solo developer ship collaborative features that would take a small backend team weeks to build from scratch. Next week we tackle indie dev growth loops.