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

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
V
V2EX
Martin Fowler
Martin Fowler
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
博客园 - 【当耐特】
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
K
Kaspersky official blog
Security Latest
Security Latest
H
Help Net Security
博客园_首页
美团技术团队
Spread Privacy
Spread Privacy
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
G
Google Developers Blog
NISL@THU
NISL@THU
爱范儿
爱范儿
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
I
InfoQ
The Cloudflare Blog
F
Full Disclosure
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

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
The Stream class in Dart
Mathieu K · 2026-05-27 · via DEV Community

We have seen the Future class in a previous publication, we can now start learning a bit more about the Stream class. In fact, the Future.asStream() method was already there to show a quick example how work a Stream.

What a difference with a Future? Well, a Future is dealing with only one event, a Stream deals with a sequence of events. This sequence of events can be created using yield*. In this case, the function needs to be marked with async*, and will return a Stream<E> where E is the event type. In short, you can see these objects like an Iterable with side effects.

A source of asynchronous data events.

-- Dart Language Documentation, Stream class

Like for the Future class, I will try to take few interesting methods/constructors from the Stream class and give some example with use cases.

Single vs Broadcast Streams

A single-subscription Stream is a finite sequence of events, having a beginning and an ending. Only one listener can be configured this kind of objects. For example, you can see that as a file, the content of this file is returned until the end.

A single-subscription stream allows only a single listener during the whole lifetime of the stream. It doesn't start generating events until it has a listener, and it stops sending events when the listener is unsubscribed, even if the source of events could still provide more. The stream created by an async* function is a single-subscription stream, but each call to the function creates a new such stream.

-- Dart Stream class

A broadcast stream is an infinite sequence of events and can allow many listeners. For example, you can see that as an active connection between a client and a server. The client can send any kind of unpredictable data or events, and the server don't control that, until one part of the connection close the exchange.

A broadcast stream allows any number of listeners, and it fires its events when they are ready, whether there are listeners or not.

-- Dart Stream class

Another great definition can be seen in Using Streams from the Dart guide.

Stream.fromFuture()

Stream.fromFuture() constructor converts a Future to a Stream object.

Future<int> t(int x) async {
  print("wait $x seconds");
  await Future.delayed(Duration(seconds: x));
  return x;
}

void main() async { 
  Stream
    .fromFuture(t(1))
    .listen(
      (event) => print("received: $event")
    );
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_from_future.dart
wait 1 seconds
received: 1

Enter fullscreen mode Exit fullscreen mode

Few code examples are using this method, but one can be seen in use_trace_precompiler_flag_test.dart where a file output is converted to a Stream. This method is helpful if one wants to use Stream features without modifying deeply an interface using Future.

Stream.fromFutures()

Stream.fromFutures() constructor converts sequence of Future object to a Stream.

Future<int> t(int x) async {
  print("wait $x seconds");
  await Future.delayed(Duration(seconds: x));
  return x;
}

void main() async { 
  Stream
    .fromFutures([
      t(1), 
      t(1), 
      t(2), 
      t(0), 
      t(2)
    ])
    .listen((event) {
      var dt = DateTime.now();
      print("received ($dt): $event");
    });
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_from_futures.dart
wait 1 seconds
wait 1 seconds
wait 2 seconds
wait 0 seconds
wait 2 seconds
received (2026-05-25 05:58:22.193): 0
received (2026-05-25 05:58:23.877): 1
received (2026-05-25 05:58:23.878): 1
received (2026-05-25 05:58:24.877): 2
received (2026-05-25 05:58:24.878): 2

Enter fullscreen mode Exit fullscreen mode

Again, there are not a lot of examples from the SDK source code, and most of them - if not all - are in stream_from_futures_test.dart. To me, this method is also a way to reuse some feature without doing deep modification on some interfaces. Can also be quite useful in mocking.

Stream.fromIterable()

Stream.fromIterable() constructor creates a Stream from an Iterable object, it can be a list or any object having the same methods/attributes than an Iterable object.

void main() async {
    Stream
      .fromIterable(
        Iterable.generate(10)
      )
      .listen(print);
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_from_iterables.dart
0
1
2
3
4
5
6
7
8
9

Enter fullscreen mode Exit fullscreen mode

Stream.periodic()

Stream.periodic() constructor creates a Stream sending periodically events. Those events are integers, starting from 0 and incremented by 1 for every new "tick".

void main() async { 
  Stream
    .periodic(Duration(seconds: 1), (count) => count )
    .take(5)
    .forEach(print);
}

Enter fullscreen mode Exit fullscreen mode

To avoid having an infinite list of numbers printed on the screen, the take() method is used to pick only 5 events and then stop the stream.

$ dart run bin/stream_periodic.dart
0
1
2
3
4

Enter fullscreen mode Exit fullscreen mode

Really useful method to create timers for example.

Stream.any()

Stream.any() method returns a boolean based on the content of the Stream, if the event one is looking for is present in it, it will return true else it will return false.

void main() async {
  print(await Stream
    .fromIterable([1,2,3,4])
    .any((x) => x >= 2 )
  );

  print(await Stream
    .fromIterable([1,2,3,4])
    .any((x) => x > 5 )
  );
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_any.dart
true
false

Enter fullscreen mode Exit fullscreen mode

What kind of use cases... Well, for testing and check if some kind of test cases have returned a specific values, it can be nice. For a real world example, I would probably use it to sanitize some input, but I'm not sure if it's efficient.

Stream.asyncMap()

Stream.asyncMap() method acts like classic map() except the function applied can be asynchronous.

Future<int> t(int s) async {
  await Future.delayed(Duration(seconds: s));
  return s;
}

void main() async {
  Stream
    .fromFutures([t(1), t(0), t(2)])
    .asyncMap((x) => x + 1)
    .listen((x) => print(x));
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_async_map.dart
1
2
3

Enter fullscreen mode Exit fullscreen mode

Stream.contains()

Stream.contains() method returns true if an event is equal to the value given to contains(), else it returns false.

Future<int> t(int x) async {
  print("wait $x seconds");
  await Future.delayed(Duration(seconds: x));
  return x;
}

void main() async { 
   print(
    Stream
      .fromFutures([
        t(1), t(2), t(3)
      ])
      .contains(1)
  );

  print(
    await Stream
      .fromFutures([
        t(1), t(2), t(3)
      ])
      .contains(1)
  );

  print(
    await Stream
      .fromFutures([
        t(1), t(2), t(3)
      ])
      .contains(0)
  );
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_contains.dart
wait 1 seconds
wait 2 seconds
wait 3 seconds
Instance of '_Future<bool>'
wait 1 seconds
wait 2 seconds
wait 3 seconds
true
wait 1 seconds
wait 2 seconds
wait 3 seconds
false

Enter fullscreen mode Exit fullscreen mode

Stream.drain()

Stream.drain() method discards all event from a stream and replace it with a specific value.

void main() async { 
  final s = await Stream.fromIterable([1,2,3,4,5]);
  print(await s.isEmpty);
  print(await s.length);

  await s.drain([]);
  print(await s.isEmpty);
  print(await s.length);

  final s2 = await s.drain([]);
  print(s2.isEmpty);
  print(s2.length);
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_drain.dart
false
5
true
0

Enter fullscreen mode Exit fullscreen mode

I'm still not really sure how this method is working. I thought calling it on the first instance would discard all events, but it was not the case, a copy of the first instance was necessary. So, I assume a stream can only be drained while it is instantiated.

Stream.every()

Stream.every() method is similar to Stream.any().

void main() async { 
  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .every((x) => x <= 1)
  );

  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .every((x) => x > 0)
  );
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_every.dart
false
true

Enter fullscreen mode Exit fullscreen mode

Stream.fold()

Stream.fold() method

void main() async { 
  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .fold<int>(0, (acc, element) => acc + element)
  );

  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .fold<int>(1, (acc, element) => acc * element)
  );

  print(
    await Stream
      .fromIterable(Iterable.generate(5))
      .map((x) => x + 65)
      .map((x) => String.fromCharCode(x))
      .fold<String>("", (acc, element) => acc + element)
  );
}

Enter fullscreen mode Exit fullscreen mode

The casting with the returned type is important there, because a Stream can return null, then, the fold() method must define the type of data returned.

$ dart run bin/stream_fold.dart
15
120
ABCDE

Enter fullscreen mode Exit fullscreen mode

Stream.forEach()

Stream.forEach() method execute a function on each element of the stream, it returns only a Future<void> when it's done.

void main() async {
    Stream
      .fromIterable([1,2,3,4,5])
      .forEach((x) => print(x)); 
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_foreach.dart
1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

Stream.listen()

Stream.listen() method listens for an event and applies a function on it. It can also deal with errors (onError) and the last event of the stream (onDone).

Future<int> t(int x) async {
  if (x>4) throw("error");
  return x;
}

void main() async {
    Stream
      .fromFutures(
        [t(1), t(2), t(3), t(4), t(5)]
      )
      .listen(
        (x) {
          print(x);
        },
        onError: (x) {
          print(x);
        },
        onDone: () {
          print("done");
        },
        cancelOnError: false
      ); 
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_listen.dart
1
2
3
4
error
done

Enter fullscreen mode Exit fullscreen mode

Stream.map()

Stream.map() method applies a function to the events from the Stream. Similar to Iterable.map().

void main() async {
    Stream
      .fromIterable([1,2,3,4,5])
      .map((x) => x + 1)
      .listen(print);
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_map.dart
2
3
4
5
6

Enter fullscreen mode Exit fullscreen mode

Stream.pipe()

Stream.pipe() method gives a way to pipe the streams into a stream consumer object. To do that, one must implement a new class using the StreamConsumer abstract class. A good use case can be found in tests/lib/async/slow_consumer_test.dart.

import 'dart:async';

class SC implements StreamConsumer<int> {
  int _counter = 0;
  num _sum = 0;

  SC();

  Future addStream(Stream s) async {
    print("add stream $s");
    await s.forEach((x) => _sum += x);
    _counter += 1;
    return s;
  }

  Future close() {
    print("close (sum: $_sum)");
    return new Future.value(_counter);
  }
}

void main() async {
    await Stream
      .fromIterable([1,2,3,4,5])
      .pipe(new SC())
      .then((x) => print("then: $x"));
}

Enter fullscreen mode Exit fullscreen mode

add stream Instance of '_MultiStream<int>'
close (sum: 15)
then: 1

Enter fullscreen mode Exit fullscreen mode

Adding a consumer in a pipe with a custom state can be helpful for many things, the use case presented in the test suite to control the data consumption speed is one of them, but we can eventually also use it to collect stats or filter different kind of requests. More examples can be found in the SDK source code, involving dart:io package and dealing with sockets and files.

Stream.reduce()

Stream.reduce() method is similar to fold() except it does not have any initial values.

void main() async { 
  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .reduce((acc, element) => acc + element)
  );

  print(
    await Stream
      .fromIterable([1,2,3,4,5])
      .reduce((acc, element) => acc * element)
  );

  print(
    await Stream
      .fromIterable(Iterable.generate(5))
      .map((x) => x + 65)
      .map((x) => String.fromCharCode(x))
      .reduce((acc, element) => acc + element)
  );
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/stream_reduce.dart
15
120
ABCDE

Enter fullscreen mode Exit fullscreen mode

Stream.take()

Stream.take() method takes only a specific amount of events from the Stream.

Future<int> t(int x) async {
  if (x>4) throw("error");
  return x;
}

void main() async {
    Stream
      .fromFutures(
        [t(1), t(2), t(3), t(4), t(5)]
      )
      .take(3)
      .listen(print);
}

Enter fullscreen mode Exit fullscreen mode

$ dart run bin/dart_take.dart
1
2
3

Enter fullscreen mode Exit fullscreen mode

Stream.transform()

Stream.transform() method applies a StreamTransformer to the Stream.

import 'dart:async';

void main() async {
    Stream
      .periodic(Duration(seconds: 1), (x) => x)
      .take(5)
      .transform(
        StreamTransformer.fromHandlers(
          handleData: (data, sink) {
            print("transform: $data");
            sink.add(data+1);
          },
          handleError: (error, stacktrace, sink) {
            sink.add("transform: error $error");
          },
          handleDone: (sink) {
            print("transform: done");
            sink.add("done");
          }
        ),
      )
      .listen((x) => print("listen $x"));
}

Enter fullscreen mode Exit fullscreen mode

At first, I wanted to create my own class implemented using StreamTransformer but for some kind of reason, it was failing. So, instead, I'm using StreamTransformer.fromHandlers() method which returns a valid StreamTransformer object that can be used with Stream.transform() method.

$ dart run bin/stream_transform.dart
transform: 0
listen 1
transform: 1
listen 2
transform: 2
listen 3
transform: 3
listen 4
transform: 4
listen 5
transform: done
listen done

Enter fullscreen mode Exit fullscreen mode

To be honest, this method was not so easy to understand on my side. I've read lot of code example to have an idea how to use it "correctly" (and I still have a doubt). Here where one can find some example from Dart SDK:

Last Words

The Stream class is almost as critical than the Future one. Dealing with a sequence of events is an important task in any modern programming language. This publication will probably be not the last one on Stream and Future classes, because there are more to learn, like Completer, StreamConsumer, StreamController, StreamIterator, StreamSink, `StreamTransformer classes and many others... Another publications will also be necessary to give real world examples using real data.

Anyway, as usual, if the previous examples and use cases presented in this post were not enough, here a list of interesting links to check:


Cover Image by Felix yu on Unsplash