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

推荐订阅源

N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
Y
Y Combinator Blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
IT之家
IT之家
V
V2EX
C
Check Point Blog
MongoDB | Blog
MongoDB | Blog
Last Week in AI
Last Week in AI
B
Blog
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
雷峰网
雷峰网

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
Dart Records & Patterns Deep Dive — Destructuring, Sealed...
kanta13jp1 · 2026-05-03 · via DEV Community

kanta13jp1

Dart Records & Patterns Deep Dive — Destructuring, Sealed Classes & Exhaustive Matching

Dart 3.0 shipped Records, Patterns, and Sealed Classes together. Used well, they eliminate entire categories of runtime errors and make state management dramatically more expressive.

Records — typed tuples without the boilerplate

// Before: untyped Map
Map<String, dynamic> getUserInfo() => {'name': 'Alice', 'age': 30};

// Dart 3: typed Record
(String name, int age) getUserInfo() => ('Alice', 30);

void main() {
  final (name, age) = getUserInfo();
  print('$name is $age years old');
}

Enter fullscreen mode Exit fullscreen mode

Named fields

({String name, int age, String email}) getUser() => (
  name: 'Alice',
  age: 30,
  email: 'alice@example.com',
);

final user = getUser();
print(user.name); // Alice

Enter fullscreen mode Exit fullscreen mode

Parsing Edge Function responses with Records

({bool ok, String? error, Map<String, dynamic>? data}) parseEfResponse(
    http.Response response) {
  if (response.statusCode == 200) {
    return (ok: true, error: null, data: jsonDecode(response.body));
  }
  return (ok: false, error: response.body, data: null);
}

Future<void> fetchDashboard() async {
  final result = parseEfResponse(await http.get(Uri.parse('...')));
  if (!result.ok) {
    print('Error: ${result.error}');
    return;
  }
  processData(result.data!);
}

Enter fullscreen mode Exit fullscreen mode

Patterns — destructuring as a first-class feature

List patterns

switch ([1, 2, 3, 4, 5]) {
  case [var first, var second, ...]:
    print('First: $first, Second: $second');
  case []:
    print('Empty');
}

Enter fullscreen mode Exit fullscreen mode

Map patterns

void processConfig(Map<String, dynamic> config) {
  switch (config) {
    case {'type': 'ai_chat', 'model': String model, 'temperature': double temp}:
      initAiChat(model: model, temperature: temp);
    case {'type': 'competitor_check', 'urls': List urls}:
      checkCompetitors(urls.cast<String>());
    default:
      throw ArgumentError('Unknown config type');
  }
}

Enter fullscreen mode Exit fullscreen mode

Object patterns

sealed class Shape {}
class Circle extends Shape { final double radius; Circle(this.radius); }
class Rectangle extends Shape {
  final double width, height;
  Rectangle(this.width, this.height);
}

double area(Shape shape) => switch (shape) {
  Circle(:final radius) => math.pi * radius * radius,
  Rectangle(:final width, :final height) => width * height,
};

Enter fullscreen mode Exit fullscreen mode

Sealed Classes — compiler-enforced exhaustiveness

sealed class AgentState {}

class AgentIdle extends AgentState {}
class AgentThinking extends AgentState {
  final String task;
  AgentThinking(this.task);
}
class AgentCompleted extends AgentState {
  final String result;
  final Duration elapsed;
  AgentCompleted(this.result, this.elapsed);
}
class AgentFailed extends AgentState {
  final String error;
  final int retryCount;
  AgentFailed(this.error, this.retryCount);
}

// Compiler guarantees all cases are covered
String describeState(AgentState state) => switch (state) {
  AgentIdle() => 'Idle',
  AgentThinking(:final task) => 'Processing: $task',
  AgentCompleted(:final result, :final elapsed) =>
    'Done in ${elapsed.inSeconds}s: $result',
  AgentFailed(:final error, :final retryCount) =>
    'Failed (attempt $retryCount): $error',
};

Enter fullscreen mode Exit fullscreen mode

Driving Flutter UI from sealed state

Widget buildAgentWidget(AgentState state) => switch (state) {
  AgentIdle() => const Icon(Icons.smart_toy_outlined),
  AgentThinking(:final task) => Column(children: [
    const CircularProgressIndicator(),
    Text(task),
  ]),
  AgentCompleted(:final result) =>
    Text(result, style: const TextStyle(color: Colors.green)),
  AgentFailed(:final error, :final retryCount) => Column(children: [
    const Icon(Icons.error, color: Colors.red),
    Text(error),
    if (retryCount < 3)
      TextButton(onPressed: retry, child: const Text('Retry')),
  ]),
};

Enter fullscreen mode Exit fullscreen mode

Guard clauses with when

List<String> categorize(List<int> numbers) => [
  for (final n in numbers)
    switch (n) {
      int x when x < 0 => 'negative',
      0 => 'zero',
      int x when x.isEven => 'positive even',
      _ => 'positive odd',
    }
];

Enter fullscreen mode Exit fullscreen mode

Pattern: a type-safe Result type

sealed class Result<T> {}

class Ok<T> extends Result<T> {
  final T value;
  Ok(this.value);
}

class Err<T> extends Result<T> {
  final String message;
  final StackTrace? stackTrace;
  Err(this.message, [this.stackTrace]);
}

Result<List<Map<String, dynamic>>> parseJson(String body) {
  try {
    final data = jsonDecode(body) as List;
    return Ok(data.cast<Map<String, dynamic>>());
  } catch (e, st) {
    return Err('JSON parse failed: $e', st);
  }
}

Future<void> loadAiProviders() async {
  switch (parseJson(await fetchProviders())) {
    case Ok(:final value):
      setState(() => providers = value);
    case Err(:final message, :final stackTrace):
      logger.error(message, stackTrace);
      showSnackBar('Failed to load');
  }
}

Enter fullscreen mode Exit fullscreen mode

Quick reference

Feature Best for
Records Multiple return values, lightweight DTOs, destructuring
List/Map/Object Patterns Data-shape branching and transformation
Sealed Classes State machines, error types, algebraic data types
Guard clauses (when) Conditional patterns
if-case Single destructure + type narrowing

Dart 3 patterns eliminate most instanceof checks, casts, and null guards — and the compiler tells you immediately when you miss a case.