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

推荐订阅源

N
News and Events Feed by Topic
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
T
Threat Research - Cisco Blogs
Cloudbric
Cloudbric
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
Intezer
Attack and Defense Labs
Attack and Defense Labs
P
Privacy International News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
V2EX - 技术
V2EX - 技术
AWS News Blog
AWS News Blog
O
OpenAI News
L
LINUX DO - 最新话题
N
News | PayPal Newsroom
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Latest news
Latest news
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
Arctic Wolf
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
T
Tor Project blog
博客园_首页
Know Your Adversary
Know Your Adversary
有赞技术团队
有赞技术团队
S
Secure Thoughts
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
T
Tailwind CSS Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
V
Visual Studio Blog
J
Java Code Geeks
Cisco Talos Blog
Cisco Talos Blog
Schneier on Security
Schneier on Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security Affairs
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
宝玉的分享
宝玉的分享
量子位
Last Week in AI
Last Week in AI
月光博客
月光博客
罗磊的独立博客
S
SegmentFault 最新的问题

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 Future class in Dart
Mathieu Kerjouan · 2026-05-26 · via DEV Community

The Future class is the main abstraction to deal with concurrency and asynchronous programming in Dart. The goal of this class is to create an asynchronous computation and deal with its return, even if it's an error or an exception.

The result of an asynchronous computation.

-- Dart Language Documentation, Future class

A lot of attributes, methods and functions can be used with this class of objects, the following sections will be the ones I think they will be the most useful to me.

Future.delayed()

The Future.delayed() constructor create a new Future executed after a defined delay. The following code will print the date after 10 seconds. It can also be used to create asynchronous sleep function. Indeed, the sleep() function defined in dart:io block the whole event loop.

void main() async {
  print("sync: ${DateTime.now()}");

  Future.delayed(Duration(seconds: 3), () {
    print("async: ${DateTime.now()}");
  });
  print("sync: ${DateTime.now()}");

  await Future.delayed(Duration(seconds: 3), () {
    print("async: ${DateTime.now()}");
  });
  print("sync: ${DateTime.now()}");
}

$ bin/delayed.dart
sync: 2026-05-24 07:02:29.298
sync: 2026-05-24 07:02:29.299
async: 2026-05-24 07:02:33.131
async: 2026-05-24 07:02:33.132
sync: 2026-05-24 07:02:33.132

What kind of use case? Well, I think one of the first we can think is to create an asynchronous sleep() function. Indeed, the one provided by dart:io package blocks the whole Dart event loop and can make things a bit complicated. Here a quick and dirty implementation of the asynchronous version:

/// An asynchronous sleep function using
/// Future.delayed(), can be used without
/// blocking the whole event loop thread.
Future<int> sleep(int s) async {
  return new Future.delayed(Duration(seconds: s), () => s);
}

Any delayed execution of function with side effect can be a good use case, like retrieving data from the web for example.

Future.microtask()

The Future.microtask() constructor schedule a computation as a micro task. The idea here is to ensure the returned value of the function from the microtask will be returned before any other asynchronous task.

void main() async {  
  Future.new(() {
    print("async: ${DateTime.now()}");
  });  

  Future.microtask(() => print("microtask: test"));
  Future.microtask(() => print("microtask: test2"));
  Future.microtask(() => print("microtask: test3"));

  await Future.delayed(Duration(seconds: 3), () {
    print("async: ${DateTime.now()}");
  });
}

$ bin/microtask.dart
microtask: test
microtask: test2
microtask: test3
async: 2026-05-24 07:10:11.098
async: 2026-05-24 07:10:14.131

Right now, I don't have any real use case in mind, but, it could probably be used when some kind of data are required before any other (e.g. credentials).

Future.value()

The Future.value() constructor returns a Future with the value passed as argument.

void main() async {  
  print(Future.value(10));
  print(await Future.value(11));
}

$ bin/value.dart
Instance of '_Future<int>'
11

Again, I'm not really sure how to use this one correctly, and in which scenario it could be useful. I'm assuming it can be needed for testing purpose, especially for mocking stuff.

Future.asStream()

The Future.asStream() method convert a Future to a Stream containing only one element.

void main() async {  
  Future.value(10)
    .asStream()
    .listen((x) => print(x));
}

$ dart run bin/as_stream.dart
10

I have few use case in mind. Firstly, when you don't want to change an interface already using a Stream and you have to use a Future somewhere. The other scenario is for testing purpose, especially for mocking.

Future.catchError()

The Future.catchError() method is used to catch errors during the execution of the Future; it acts like a try/catch clause.

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

void main() async { 
  for (var i in Iterable.generate(10)) {
    var ret = await t(i)
      .catchError(
        // must reture a Future<int> to catch the error
        // correctly
        (err) async {
          print(err);
          return -1;
        }, 
        test: (_) => true
      )
      print(ret);
    }
}

The value returned by the catchError() anonymous function must have the same type than the one returned by the Future. If the future returns a Future<int> then the function defined in the catchError() method must also returns a Future<int>. Not respecting this rule will raise an exception.

$ dart run bin/catch_error.dart
0
1
2
3
4
5
6
error
-1
error
-1
error
-1

Many use case there, this is in fact, probably a fundamental method to use in any software. Instead of using a try/catch, using a "pipeline" to catch it is more elegant.

Future.then()

The Future.then() method returns and alter the value returned by the Future.

Future<int> t(int x) async {
  return x;
}

void main() async { 
  for (var i in Iterable.generate(10)) {
    var f = await 
      t(i)
      .then((x) => x+1);
    print("i=${i}: f=${f}");
  }
}

$ dart run bin/then.dart
i=0: f=1
i=1: f=2
i=2: f=3
i=3: f=4
i=4: f=5
i=5: f=6
i=6: f=7
i=7: f=8
i=8: f=9
i=9: f=10

Again, this method seems to be quite important and fundamental. It can be used for example to modify the returned value of some specific function, useful in real world application when an application is updated, but we don't want to change the whole interface. It can also be useful in testing context.

Future.onError()

The Future.onError() method is quite similar than the catchError() seen previously, but permitting a fine grained error handling.

Future<int> t(int x) async {
  if (x%2 != 0) return x;
  throw("error");
}

void main() async { 
  for (var i in Iterable.generate(2)) {
    var f = await 
      t(i)
      .onError(
        (err, trace) {
          print("$err, $trace");
          return -1;
        },
        test: (_) => true
      );
    print("i=${i}: f=${f}");
  }
}

The stack trace can also be available on the catchError() method.

$ dart run bin/on_error.dart
error, Error
    at Object.throw_ [as throw] (https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:3803:11)
    at blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:110:23
    at https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40935:13
    at https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40945:7
    at Object._asyncStartSync (https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40893:5)
    at Object.t (blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:116:18)
    at blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:140:154
    at https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40935:13
    at https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40945:7
    at Object._asyncStartSync (https://stable.api.dartpad.dev/artifacts/dart_sdk_new.js:40893:5)
    at Proxy.main$ (blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:164:18)
    at Object.main$ [as main] (blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:53:10)
    at runMainAndHandleErrors (https://stable.api.dartpad.dev/artifacts/ddc_module_loader.js:1557:45)
    at LibraryManager._runMain (https://stable.api.dartpad.dev/artifacts/ddc_module_loader.js:1579:9)
    at LibraryManager.runMain (https://stable.api.dartpad.dev/artifacts/ddc_module_loader.js:1593:12)
    at DartDevEmbedder.runMain (https://stable.api.dartpad.dev/artifacts/ddc_module_loader.js:2140:22)
    at contextLoaded (blob:null/f8144f6a-c3bf-4e21-9dbc-0c8ed71a4da1:181:19)
    at Object.execCb (https://dartpad.dev/require.js:8:16727)
    at e.check (https://dartpad.dev/require.js:8:10499)
    at e.<anonymous> (https://dartpad.dev/require.js:8:12915)
    at https://dartpad.dev/require.js:8:1542
    at https://dartpad.dev/require.js:8:13376
    at each (https://dartpad.dev/require.js:8:1020)
    at e.emit (https://dartpad.dev/require.js:8:13344)
    at e.check (https://dartpad.dev/require.js:8:11058)
    at e.enable (https://dartpad.dev/require.js:8:13242)
    at e.init (https://dartpad.dev/require.js:8:9605)
    at a (https://dartpad.dev/require.js:8:8305)
    at Object.completeLoad (https://dartpad.dev/require.js:8:16151)
    at HTMLScriptElement.onScriptLoad (https://dartpad.dev/require.js:8:16882)
i=0: f=-1
i=1: f=1

Same use case than catchError() method, but it could be used when one requires a fine grained exception handler.

Future.timeout()

The Future.timeout() method ensure the future will be executed in a specific amount of time.

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

void main() async { 
  for (var i in Iterable.generate(5)) {
    print(i);
    var f = await 
     t(i)
     .timeout(Duration(seconds: 2),
             onTimeout: () {
               print("timeout");
               return -1;
             });
    print("i=${i}: f=${f}");
  }
}

$ dart run bin/timeout.dart
0
i=0: f=0
1
i=1: f=1
2
i=2: f=2
3
timeout
i=3: f=-1
4
timeout
i=4: f=-1

This method seems to be also fundamental, especially when dealing with remote API, or dealing with huge data. Indeed, not everyone got a great internet connection, and the delay to retrieve some information can take a while. In this situation, a timeout must be configured to avoid wasting too much time fetching data you will probably never have. Especially helpful in synchronous call with side effects.

Future.whenComplete()

The Future.whenComplete() method is equivalent to the finally clause.

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

void main() async { 
  await t(10)
    .timeout(Duration(seconds: 1), 
     onTimeout: () {
       print("timeout...");
       return -1;
    })
    .whenComplete(() {
      print("close actions");
    });
}

$ dart run bin/when_complete.dart
wait 10 seconds
timeout...
close actions

If one needs to deal with some last actions to execute anytime, even after a failure, this method seems the best to use. It can be used to explicitly close a connection or close a file descriptor.

Last Words

The Future class is a critical part of any Dart application. The previous examples are only a small glimpse of what can be done with it, and if one wants to know more about them, I highly recommend the following links:

  • Future class implementation source code from the Official Dart SDK repository, where you will find the implementation of the class itself;

  • Future Test Suite source code directory, check all files prefixed by future*, where you will find all test cases, useful to have real world example.

The next publication will be on the Stream class, another important part of Dart ecosystem.


Cover Image by Chris Liverani on Unsplash