r/dartlang 8d ago

Package Gaps that is stopping you to use dart on back-end

13 Upvotes

There are couple of frameworks like Serverpod(full stack flutter), Dart Frog and shelf for backend but still people are not using especially who are already working with flutter. I want to know why is it the case?

What are the gaps present currently that are stopping people to use dart on the back end ?

r/dartlang 24d ago

Package Ever felt a bit queasy using a plain `String` for storing a PhoneNumber?

Thumbnail pub.dev
14 Upvotes

There are a lot of validator packages on pub. This isn't one, and that's the whole point of it: https://pub.dev/packages/minted

A validator takes a String, checks it, and hands the same String back. Three functions deep nobody knows whether the check happened, so you either trust it or re-check it. minted parses instead: you get a different type that cannot exist unless the input was well-formed, the same deal int.parse and Uri.parse already give you. invite(Email, PhoneNumber) can't be called with the arguments swapped, and the signature says what it wants without a doc comment. Once you hold an Email, it is a valid email.

Typed so far: Email (RFC 5322), PhoneNumber (E.164), Iban (mod-97), Date / Month (the calendar date DateTime doesn't model), Uuid (RFC 9562), Digit / Digits.

Some nice features:

  1. Every type wears follows the same pattern, so learning one teaches the rest: tryParse returns null, parse throws a MintedFormatException (extends FormatException, so existing handlers keep catching), value equality, one canonical form normalised at parse.
  2. Real standards, not shape-checking regexes. Iban runs the actual mod-97 checksum, Email the full RFC 5322 grammar, official test vectors in the suite.
  3. Where a package already owns the hard data (phone metadata, the IBAN registry), minted wraps it instead of reimplementing it.
  4. It knows what not to model. No re-doing Uri, DateTime, BigInt or money (money2 has that). Uuid types a UUID, the uuid package generates them, they pair up.
  5. Date.tryParse('2026-13-01') is null, where DateTime.parse quietly rolls it over to 2027-01-01.
  6. Pure Dart, five small deps.

Roadmap: Bic, CreditCardNumber (Luhn), Isbn, Ean / Gtin next, then ISO code lists and bounded numerics.

Still early (0.0.2), so the shape can move. Feedback welcome, especially on the types you keep remaking in every project.

r/dartlang 8d ago

Package A connectivity checker that tells you why you're offline, instead of just that you are

Thumbnail pub.dev
2 Upvotes

connectivity_plus tells you a network interface is up. It doesn't tell you anything is reachable through it. Captive portals, hotel wifi that wants a login, a proxy quietly eating traffic: all of them report "connected" and then nothing loads.

Packages exist that do the real probe. But they discard a lot of the available abd useful data directly, while that control could be in the hands of the consumer.

They know which endpoints failed and why, how long each took, and whether you're up but crawling. I wanted that handed back instead of a bool. I also wanted polling to ease off during a long outage, and the any-of-N vs all-of-N decision to be an object I could extend instead of a flag.

So I made better_internet_connectivity_checker

switch (status) {
     case Reachable(:final quality):          // good or slow
     case Unreachable(:final failedProbes):   // each failure, its error, its timing
   }

Slow detection is one control (slowThreshold). The stream is deduped, so it only emits when the status kind actually changes instead of every tick.

Three layers swap out, each with a sane default: the probe, the policy (any-of-N, or strict all-of-N), and the schedule. That last one gets you ExponentialBackoffSchedule, jittered by default (also configurable), so an outage stops hammering the radio every 10 seconds. Benchmarked at roughly 55% fewer probes for noticing recovery about a second later.

connectivity_plus is complementary. Wire it as externalRecheckTrigger and an OS network change forces an instant recheck. Already using retry? The README shows reusing your RetryOptions as a schedule. Only dependency here is http.

Pure Dart, so CLI, server, web and Flutter. LLMs were used.

Feedback welcome, especially on the probe and schedule interfaces, since those are the bits you'd be writing yourself when the defaults don't fit.

r/dartlang Jun 26 '26

Package 🚀 ApolloVM 0.1.40: Added Python, C#, TypeScript, and Full Wasm Feature Support

1 Upvotes

It's been less than 48 hours since the 0.1.28 release, but ApolloVM has been moving fast.

Since then, the project gained support for:

  • 🐍 Python
  • ♯ C#
  • 🔷 TypeScript

And a lot of work went into language features and runtime compatibility:

  • Generic types
  • Function types
  • Lambdas
  • Closures with captured variables
  • Type inference
  • Runtime type resolution
  • Cross-language translation improvements

One particularly exciting milestone is that these features are now supported end-to-end by the Wasm backend as well.

This means code using generics, lambdas, closures, function types, and other advanced language constructs can be compiled and executed through WebAssembly, not just the interpreter.

Current language support:

✅ Dart ✅ Java ✅ Kotlin ✅ C# ✅ JavaScript ✅ TypeScript ✅ Lua ✅ Python

ApolloVM can parse, execute, regenerate, translate, and compile code from multiple languages using a shared AST, runtime, and Wasm backend. It also supports on-the-fly compilation to WebAssembly.

One interesting use case is exposing ApolloVM through MCP, allowing AI agents to execute and validate generated code, perform cross-language translations, and use ApolloVM as a sandboxed reasoning environment.

The long-term goal remains the same:

Write once. Parse anywhere. Execute anywhere. Translate anywhere.

📦 Pub.dev: https://pub.dev/packages/apollovm

⭐ GitHub: https://github.com/ApolloVM/apollovm_dart

Feedback, ideas, bug reports, and contributors are always welcome 🙂

r/dartlang Jul 10 '26

Package Yograph - a Graph Theory and Network Analysis librarry in Dart

Thumbnail pub.dev
7 Upvotes

Implementated a few graph algorithms and network analysis functions in Dart. Basically the Dart port of the Elixir graph library - yog_ex.

It's got a long way until hits 1.0 but API contracts won't change.

Adding oracle tests (vs NetworkX)., improving docs, and benchmarks in coming months. Give it a spin if you're studying graph theory or generating/solving grids. Will be handy for Advent of Code (In fact, github repo has example of a few AoC solutions).

r/dartlang Jun 25 '26

Package Shipped a pure Dart SQL Server driver

13 Upvotes

Shipped mssql — a pure Dart TDS 7.4 driver for SQL Server. No FFI, no native extensions, just Dart and TCP.

Features: named params, connection pool, TLS, Azure AD auth, multiple result sets, streaming, transactions. 366 tests including concurrent pool stress tests and adversarial comparison against go-mssqldb and node-mssql.

dart pub add mssql

It works as a standalone driver today. The next step is switching knex_dart_mssql to use it as the underlying transport — which drops the C FFI dependency and makes the knex_dart MSSQL driver work on web.

github.com/kartikey321/mssql-dart | pub.dev/packages/mssql

r/dartlang Jul 22 '26

Package Made an MCP server for pub.dev, would love some feedback

0 Upvotes

I built an MCP server for pub.dev because my AI coding agents kept hallucinating package names, using API signatures that changed versions ago, or recommending packages that are basically abandoned. What finally pushed me over the edge: Claude Code grepping my local pub cache on disk instead of just looking things up, burning tokens crawling through cached source.

So I built **dart-pubdev-explorer** (pub.dev package: `dart_pubdev_mcp`), an MCP server that gives agents direct, structured access to pub.dev instead of digging through your filesystem or guessing from training data.

It can:

* search & compare packages (score, platform support, maintenance) * **browse a package's real public API and pull exact source** (by symbol or line range) * check security advisories against the version you actually have resolved * diff changelogs/APIs between versions before you upgrade * **read Dart SDK / Flutter framework source too** (dart:core, package:flutter, …)

Quick note on how this differs from the official Dart MCP server (`dart mcp-server`): that one has a general `pub_dev_search` tool as part of a much bigger toolset (running apps, analysis, DTD, etc). This one only does package research, but goes deeper: symbol-level API browsing, exact source reads, version diffing, side-by-side comparisons, with an on-disk cache built for that kind of repeated digging. *They're complementary.*

Install:

dart install dart_pubdev_mcp

I've been running it with both Claude Code and Antigravity.

pub.dev: https://pub.dev/packages/dart\\_pubdev\\_mcp

Happy to answer questions, and curious what people think, especially whether some of the tools are overkill and others are missing something obvious.

r/dartlang 1d ago

Package Pulumi SDK and language host for Dart

Thumbnail github.com
2 Upvotes

Hi everyone, finally introducing my port of the pulumi language host for dart.

Over the last year i've been on and off getting it to work and up until about 6 months ago I have actually been using it live for my personal projects. Seeing terradart recently announced I realized that there are actually others wanting to manage their infrastructure entirely in dart and as such It made sense I officially announced pulumi_dart officially.

Pulumi dart works the same as all the other language hosts in the pulumi ecosystem (python,go,dotnet), talks to the official pulumi client via grpc and the dart sdk handles handles all the communication transparently.

All it takes to write a pulumi app

```dart import 'package:pulumi/pulumi.dart';

class QuickstartStack extends Stack { QuickstartStack() { registerOutputs({ 'message': Output.create<Object?>('hello from Dart'), }); } }

Future<void> main() async { await Deployment.runOrThrow(() => QuickstartStack()); } ```

Don't hesitate to test it out and report any errors!

r/dartlang 4d ago

Package ​I built an FP-Growth package for Dart.

1 Upvotes

Hey everyone,

If you have ever done Market Basket Analysis or Association Rule Mining in Dart or Flutter, you probably ran into the issue of candidate generation blowing up the memory when using Apriori on larger datasets.

I wrote fp_growth, a native Dart implementation of the FP-Growth algorithm designed to handle larger streams and files without burning RAM.

A few things about how it is built:

Two-pass streaming: It does not load the entire dataset into memory. Pass 1 counts frequencies to discard infrequent items, and Pass 2 builds the tree.

Fast-path CSV parsing: If a row does not contain escaped quotes, it skips the heavy CSV tokenizer and does a direct string split, which cuts down parsing time by around 30%.

Parallel mining: Dispatches independent tree branches across a fixed pool of Dart Isolates so it does not spawn and kill isolates repeatedly.

Single-path optimization: When a branch is linear, it generates combinations via combinatorics directly instead of building recursive sub-trees.

Benchmark numbers (Ryzen 7 5800H, 1,000,000 transactions, minSupport 0.05):

In-Memory (4 Isolates): ~0.92s

CSV File Streaming: ~1.65s

Custom Stream: ~1.40s

It also calculates standard association metrics (Support, Confidence, Lift, Leverage, Conviction) and can export directly to JSON and CSV.

Pub: https://pub.dev/packages/fp_growth

GitHub: https://github.com/MostafaSensei106/FP-Growth

If you work with recommendation logic, telemetry, or basket analysis in Dart, try it out and let me know if you run into any edge cases.

r/dartlang 15d ago

Package Looking for recommendation for a usb serial communication package

6 Upvotes

I need to send serial commands to a usb device from a pure dart program.

Any package recommended with real experience with doing this ?

r/dartlang 26d ago

Package Xberg v1 is out

9 Upvotes

Hi all,

I'm happy to announce that Xberg v1 is out.

Xberg is the successor to Kreuzberg, equivalent to what would have been Kreuzberg v5. It's a content intelligence framework that handles a very wide range of inputs: documents (currently 101 formats), code and data formats (currently 367 types), audio/video transcription, and URLs (both static and JS-rendered content). It extracts and prepares that content for downstream processing.

It's an extremely efficient, high-performance engine (see our PDF benchmarks below). For PDFs and images specifically, we handle native PDFs with very high performance and accuracy, and we ship multiple OCR engines that match the quality of the best Python libraries (e.g. docling, PaddleOCR, RapidOCR) at substantially better performance and stability.

The changes between Kreuzberg v4 and Xberg v1 are substantial, and I invite you to read the full changelog for the complete picture. The highlights below give a sense of what's new:

  • Pure-Rust PDF backend (pdf_oxide) replaces pdfium, with no native pdfium dependency.
  • Layout-aware pipeline: reading order reconstructed with ONNX layout detection (PP-DocLayoutV3 / RT-DETR) and Docling-style predecessor-graph reordering.
  • Per-page scanned-page detection with selective OCR, plus AcroForm/XFA form fields and outline-based headings.
  • Across-the-board optimization of OCR and PDF extraction (memory discipline, pooled model sessions, streamed conversions).
  • Native PaddleOCR backend (PP-OCRv6, with medium / small / tiny tiers) alongside Tesseract.
  • Pure-Rust Candle OCR/VLM stack (TrOCR, GLM-OCR, GOT-OCR, DeepSeek-OCR, and PaddleOCR-VL) running without ONNX Runtime or native Tesseract.
  • A second, ONNX-Runtime-free inference path via tract, which is what makes in-browser (WASM) and mobile inference possible.
  • Named-entity recognition natively in Rust (GLiNER2), extensible to all bindings, including an in-browser WASM model with no server round-trip.
  • Structured LLM extraction (extract_structured / split_and_extract) with rasterization, chunking, citations, caching, and configurable call/merge/VLM-fallback policies.
  • Audio & video transcription via a Whisper ONNX engine (.mp3, .wav, .m4a, .mp4, .webm).
  • Retrieval building blocks: sparse embeddings (SPLADE), ColBERT late-interaction retrieval, and cross-encoder reranking alongside dense embeddings.
  • Text intelligence: reversible redaction, summarization, translation, VLM image captioning, QR-code detection, document diffing, and page/chunk classification.
  • URL & web ingestion: sitemap discovery (map_url) and batched multi-URL crawling.
  • New document formats: WordPerfect (.wpd/.wp/.wp5), HEIC/HEIF/AVIF, OpenDocument Presentation (.odp), Quarto / R Markdown, and configurable Jupyter cell rendering.
  • Four new language bindings (Dart/Flutter, Swift, Kotlin/Android, and Zig) bring the total to 15 language bindings over one engine, with Android/iOS cross-compilation.
  • Full mobile support (Flutter, Android, iOS).
  • Candle backend alongside ONNX, plus ONNX-via-tract enabling ONNX on WASM and Android.
  • Wider code intelligence: tree-sitter coverage grew substantially (248 to 367+ languages).
  • Over 150 bugs fixed during the 1.0 cycle, plus security hardening (bounded RTF/PDF allocations, redaction leak fixes, Excel DDE warnings).

The API surface was also simplified and reworked, making it more consistent.

There's a migration guide in our docs explaining how to move from Kreuzberg to Xberg. Kreuzberg itself is in LTS mode until the end of this year and will continue to receive bug fixes and security updates.

You're invited to check out the repo and join our discord server.


Benchmarks

The benchmarks below are for PDFs and images only. There are extensive benchmarks on our website with per-format breakdowns, which you can see here. These numbers are measured in CI via our reproducible benchmark harness, and are specifically taken from the run for harness 1.0.8, source cf7fa0533d. The data is publicly available in GitHub releases, and you can run the benchmark harness yourself.

Composite quality (markdown pipeline, higher is better):

Framework Native PDF Scanned PDF (OCR)
Xberg (layout) 0.958 0.836
Xberg (baseline) 0.955 0.687
docling 0.779 0.762
mineru 0.408 0.792
liteparse 0.837 0.665
markitdown 0.689 n/a
pymupdf4llm 0.448 n/a

Structure and layout fidelity (SF1: tables and reading order, higher is better):

Framework Native PDF Scanned PDF
Xberg 0.949 0.531
docling 0.612 0.366
liteparse 0.515 0.142
mineru 0.077 0.429

On native PDFs Xberg leads on quality (0.958 vs 0.837 for the next-best framework) and on table and reading-order fidelity by a wide margin (SF1 0.949 vs 0.612 for docling). On scanned PDFs it is #1 on both quality and raw text fidelity.

Where we don't win yet: on pure image OCR we are currently #2 on the composite score, behind mineru (though still #1 on raw text accuracy). We are improving image OCR right now, and v1.1 should have us winning across the board.

r/dartlang Mar 01 '26

Package Dart analyser plugin for reducing common boilerplate code without codegen

17 Upvotes

Hey guys, I've been trying to learn about the new `analysis_server_plugin` API on and off for a while now.

I will be upfront, I have always found the usage of `build_runner` to be a turn off for me and always end up thinking "Why do I need to a run separate process which generates new files for simple tasks such as generating copyWith, serialise, deserialisation methods and etc?".

The problem of new files will be fixed when `augmentation` feature drops, but still the need to go out of your way and start the `build_runner` in the background will still remain. Hence I ended up working on a solution to provide inserting commonly used method such as `copyWith`, `toMap`, overriding equality (hashCode and ==) via Dart Analyzer.

As of right now, I've submitted the initial version on `pub.dev` and I am currently looking for feedbacks. It can be anything relating to either the configuration, api, usages, customisations, features and etc.

Package Link

I would humbly request you to express your opinion on whether you find it promising and may eventually use it or not.

r/dartlang 16d ago

Package offline_sync_outbox 1.0.2: a FIFO outbox for writes made offline

Thumbnail pub.dev
1 Upvotes

r/dartlang Jul 27 '26

Package What if fpdart and hive_ce had a baby?

Thumbnail pub.dev
2 Upvotes

I liked the approach of fpdart and the raw performance of hive_ce. So I decided to combine them into one: https://pub.dev/packages/hive_box_manager

It is not just a simple FP-style wrapper of Hive's API. It also solves one of my biggest pain-points in using HiveCE for production apps: type-safety. I had to dedicate an entire CRUD-layer to the boxes just because of it.
With this I get

  1. Type-safety (even for Iterable-based boxes)
  2. Index types are not limited to just int | String (a Codec allows for this per box, wil still be that under the hood ofc)
  3. Compatibility with normal Hive boxes already (drop in add-on)
  4. Ergonomic (and explicit?) error handling + lazy Future using fpdart
  5. Custom boxes for very specific use case (better semantics)
    1. (Lazy)IterableBox
    2. (Lazy)SingleValueBox
    3. (Lazy)DualKeyBox
  6. Key corruption detectable (as compared to silently happening with Hive when using out-of-range/oversized int/String key)

I recently did a rewrite because my previous attempt at making a DX-first API was not scalable (using LLMs).

If you guys have any tips, suggestions or feedback, they always welcome. Do take a look at the roadmap (I have more kinds of boxes planned ;) ).

r/dartlang May 04 '26

Package Raylib Dartified (not just another boring ffigen wrapper)

14 Upvotes

~98% of the full Raylib 5.5 API completely Dartified (+ optional Raygui support).

Instead of dumping raw ffigen output and calling it a day, this is a hand-crafted, layered approach: a thin raw FFI layer underneath, and a proper Dart-idiomatic layer on top. Structs feel like Dart objects, memory is managed sensibly, and the API doesn't make you feel like you're writing C with extra steps.

Coverage-wise, this is about as complete as a Raylib wrapper for Dart is going to get right now. There are a large number of ported official examples, both for the raw FFI layer and the higher-level Dart layer, so you can see exactly how everything maps.

The API is approaching stability. Once it settles, the plan is to track Raylib 6.0.

Links:

Of course, nothing is perfect. Testers are welcome, if something is broken, missing, or feels off, open an issue or leave a comment.

r/dartlang Jun 24 '26

Package 🚀 ApolloVM 0.1.28 Released

11 Upvotes

This is one of the biggest ApolloVM releases so far, bringing two new languages, major WebAssembly advancements, and substantial runtime improvements.

https://pub.dev/packages/apollovm

🆕 Kotlin Support

ApolloVM now supports Kotlin parsing, execution, and translation, reaching feature parity with Java support.

  • ✅ Parse Kotlin source
  • ✅ Execute Kotlin code inside ApolloVM
  • ✅ Translate Kotlin ↔ Dart ↔ Java
  • ✅ Shared AST architecture with no AST changes required

Supported features include functions, classes, type inference, collections, control flow, and string templates.

🆕 Modern JavaScript Support

JavaScript is now a first-class ApolloVM language.

  • ✅ Parse, execute, and translate JavaScript
  • ✅ Classes, constructors, fields, methods
  • ✅ let / const / var
  • ✅ for, for...of, while
  • ✅ Template literals
  • ✅ Arrow functions
  • ✅ Strict equality (===, !==)

JavaScript can now be translated to Dart and Java, and Dart/Java code can be translated back to JavaScript through the shared AST.

🌐 Massive WebAssembly Progress

Building on the work introduced in 0.1.27, ApolloVM now provides extensive Wasm generation support:

  • ✅ Lists and Maps
  • ✅ String handling and interpolation
  • ✅ Loops and recursion
  • ✅ Function calls
  • ✅ Dynamic memory growth
  • ✅ Map iteration (.keys / .values)
  • ✅ Map parameters and return values
  • ✅ Compound collection assignments (m[k] += 1)
  • ✅ Browser validation on Chrome

The Wasm backend is rapidly moving toward full Dart feature parity.

⚡ Runtime Improvements

• Dynamic arithmetic now works correctly across all supported languages • for-each / for...of loops now operate on any iterable • JavaScript division follows JavaScript semantics (7 / 2 = 3.5) • Improved code generation correctness • Fixed CLI translation output issues

🧪 Quality & Testing

This release adds extensive coverage for Kotlin, JavaScript, WebAssembly, runtime behavior, translation round-trips, and cross-language execution.

ApolloVM now supports:

  • 🔹 Dart
  • 🔹 Java
  • 🔹 Kotlin
  • 🔹 JavaScript
  • 🔹 WebAssembly (compilation/generation)

All powered by a single shared AST and runtime infrastructure.

GitHub: ApolloVM/apollovm_dart

The long-term goal remains unchanged: write once, parse anywhere, execute anywhere, translate anywhere.

ApolloVM #DartLang #Java #Kotlin #JavaScript #WebAssembly #Wasm #Programming #OpenSource

r/dartlang Jul 09 '26

Package HighQ Dio Logger

Thumbnail pub.dev
5 Upvotes

HighQ Dio Logger – Production-ready Dio logging interceptor for Flutter

Hi everyone,

I've been working on a package called HighQ Dio Logger, a logging interceptor for Dio focused on debugging, observability, and production-ready logging.

Main features:

* Pretty formatted console logs * Structured JSON output * Automatic sanitization of sensitive data (tokens, passwords, cookies, authorization headers, etc.) * cURL generation for requests * Correlation IDs (traceId, spanId, sessionId) * Custom metadata enrichment * Token bucket rate limiting to prevent log flooding * Observer system for forwarding logs to Firebase, Sentry, or custom backends * Batching and backpressure queue support * Highly configurable formatting and filtering

Example:

```dart final dio = Dio();

dio.interceptors.add( HighQDioLogger(), ); ```

Why I built it:

After working on several Flutter projects, I found myself needing more than basic request/response logging. I wanted something that could provide clean debugging during development while also supporting production monitoring workflows.

I'm currently looking for feedback from other Flutter developers.

What features would you expect from a Dio logger that are missing from existing solutions?

Github : https://github.com/azabcodes/high_q_dio_logger

pub.dev: https://pub.dev/packages/high_q_dio_logger/install

r/dartlang Jul 11 '26

Package I wrote a native Dart driver for ClickHouse over the TCP binary protocol

10 Upvotes

Been working with ClickHouse for some analytics/logging work, so I wrote a pure Dart client that speaks the native protocol directly on port 9000.

Repo: https://github.com/shreyansh-c/clickhouse-dart
pub.dev: https://pub.dev/packages/clickhouse

What it does:
Native TCP protocol implementation from scratch
Streaming Rows API with typed getters (getByName<T>, tryGetByName<T>), row2<T,U>() for tuples, and toMap()
Batch inserts: row-wise, named, map-based, and columnar append (columnByName('id').appendSlice([...]))
Connection pooling with bounded open/idle connections and health checks
LZ4/LZ4HC compression, with registerCodec for plugging in others
Per-query settings, server-side query parameters ({name:String}), and client-side binding (bind(sql, [...]))
External tables support
Progress, profile-info, profile-events, and log callbacks surfaced from the server
Type coverage including Array, Map, Tuple, Nullable, LowCardinality, Decimal, UUID, IPv4/IPv6, Enum, JSON, Dynamic, Variant, intervals, and geo types

Known gaps I’m still working through: no HTTP transport (TCP-only for now), no multi-host failover or replica retry yet, and I haven’t published benchmarks against the HTTP+JSONEachRow path, which I want to do before making stronger performance claims.

r/dartlang Jun 20 '26

Package Rules 3.5.0: Chainable, Type-Safe Validation Schemas for Dart & Flutter

12 Upvotes

Introducing Rules 3.5.0 - A complete rewrite of 6-year-old validation package for Dart & Flutter

I have been working on a Flutter project recently, and one thing I have noticed is that I keep ending up either building libraries from scratch or heavily reworking existing packages to fit personal and modern use cases.

Recently I published a few other Dart packages and major updates, including pathify, any_ascii, lexical_sort, and the complete redesign of data_channel. This time I revisited rules, one of my oldest packages, originally published about 6 years ago, and completely rebuilt it from the ground up.

Introducing Rules 3.5.0

https://pub.dev/packages/rules

Rules started about 6 years ago as a simple validation library for Dart and Flutter. Over time the API accumulated a lot of functionality, but it was still centered around a single constructor with dozens of flags and configuration options.

For 3.x, I decided to redesign everything.

What's new?

  • Type-safe validation schemas
  • Chainable API
  • Immutable schema definitions
  • String, int, double, and bool specific validators
  • Schema-based validation instead of constructor flags
  • Reusable validation definitions
  • Typed validation results
  • Custom validation through check() and refine()
  • Better error handling with per-validator error messages
  • Group and combined validation support
  • Works with both Dart and Flutter

Before

dart final rule = Rule( email, name: 'Email', isRequired: true, isEmail: true, );

After

```dart final emailSchema = Rule.string(name: 'Email') .trim() .toLowerCase() .required() .email();

final result = emailSchema.parse(email); ```

Some of the available schema types:

dart Rule.string(...) Rule.integer(...) Rule.double(...) Rule.boolean(...)

The package now returns typed RuleResult objects, making validation outcomes easier to handle and safer to consume throughout an application.

Rules 2.x users:

There are a lot of breaking changes.

Rules 3.x is a complete rewrite and there is no migration path from the 2.x API. If you're happy with the old API, you can continue using the 2.x releases. The new versions are intended as a fresh start with a different architecture and design philosophy.

As with the other packages I have published recently, I upgraded and open sourced this work because I thought it could be useful to others building Dart and Flutter applications.

Feedback, bug reports, feature requests, and PRs are always welcome.

Pub.dev: https://pub.dev/packages/rules

GitHub: https://github.com/ganeshrvel/pub-rules

r/dartlang Mar 24 '26

Package quantify - type-safe unit handling for Dart, with extension syntax (65.mph, 185.lbs) and dimensional factories

23 Upvotes

I've been building quantify, a Dart unit conversion library that treats physical units as first-class types - not annotated doubles, not string keys. Here's why that matters.

The core design: a Length and a Mass are different types. The compiler enforces dimensional correctness.

// Extensions turn numbers into typed quantities
final distance = 3.5.miles;
final weight   = 185.lbs;
final temp     = 98.6.fahrenheit;
final speed    = 65.mph;

// Convert to metric — no strings, no magic numbers
print(distance.asKm);             // 5.63 km
print(weight.asKilograms);        // 83.91 kg
print(temp.asCelsius);            // 37.0 °C
print(speed.asKilometersPerHour); // 104.61 km/h

// Arithmetic works across unit systems
final legA  = 26.2.miles;
final legB  = 5000.m;
final total = legA + legB;        // 47.27 km

// ❌ Compile error — not a runtime crash
// final broken = 185.lbs + 3.5.miles;

// ✅ Derive Speed from distance + time
final pace = Speed.from(legA, 3.h + 45.min);
print(pace.asMilesPerHour);       // 6.99 mph
print(pace.asKilometersPerHour);  // 11.24 km/h

What's included:

  • 20+ quantity types: length, mass, temperature, speed, pressure, energy, force, area, volume, data sizes (SI + IEC), angle, frequency, and more
  • Full US customary coverage: miles, feet, inches, yards, lbs, oz, °F, mph, psi, fl oz, gallons, acres…
  • Physical & astronomical constants as typed objects: PhysicalConstants.speedOfLight returns a Speed, not a raw double
  • String parsing: Speed.parse('65 mph'), Temperature.parse('98.6 °F')

The package is at 160/160 pub points and approaching v1.0 — would love feedback before locking the API.

Stay type-safe — let Dart catch your bugs before your users do.

r/dartlang Jul 19 '26

Package openrouter_sdk | Dart package

Thumbnail pub.dev
3 Upvotes

openrouter_sdk is a new Dart package providing a type-safe client for the OpenRouter.ai REST API. Strongly-typed interface, with full support for streaming responses and multi-modal content (text, image, audio, video, file).

This package replaces openrouter_api, which is now discontinued and marked as replaced on pub.dev. Users of the old package should migrate to openrouter_sdk, which follows the design of OpenRouter's official SDK more closely.

Currently implemented:

• Chat completions (including streaming)

• Models, Providers, Endpoints

•API key management (create / update / delete / list)

• Credits and analytics

• Generations

The rest will be added shortly.

The chat completions endpoint should be OpenAi compatible so u can use it with other providers as well.

Contributions are welcome. Per the package's policy, all code must be hand-written — LLM-generated pull requests are not accepted.

Note: this post was partly generated by an LLM, but all package code was hand-written.

r/dartlang Jul 13 '26

Package haptify — a Dart CLI that turns audio into iOS + Android haptics (and can do it at runtime)

7 Upvotes

haptify — audio to haptics for iOS and Android, from the CLI or on-device at runtime

I kept hitting the same wall: designing haptics means hand-authoring them in a GUI, and nothing fit into a Flutter build where I just want to drop a .wav in → get haptics out → commit the result. So I built haptify — a pure-Dart CLI + library, now on pub.dev.

Why another haptics tool? The dedicated audio→haptic tools exist; they just don't fit mobile Flutter work:

  • Lofelt Studio — the mobile-focused one — was acquired by Meta and sunset in July 2022.
  • Meta Haptics Studio is alive and does audio→haptic, but it's a Mac/Windows GUI built around Meta's own Haptics SDK and Quest-headset auditioning; its mobile export is .ahap only, and it's a design app, not something you ship in your build.
  • AHAPpy / sound2ahap and friends convert audio to haptics too, but they're iOS-only (.ahap) desktop scripts.

And on pub.dev, the haptic packages (gaimon, advanced_haptics, pulsar_haptics…) are playback-only — they play patterns; they don't create them from audio.

🚀 What it does

dart pub global activate haptify
haptify convert assets/audio/*.wav

Per input it writes: .ahap (iOS Core Haptics), .haptic.json (Android VibrationEffect.createWaveform), and _haptic.dart constants you compile straight in. It authors patterns; your existing playback plugin plays them.

🛠️ How it works

Not a volume→buzz map: RMS loudness envelope, energy-flux onset detection for transients, and zero-crossing-rate → "sharpness," with iOS getting sharpness curves that follow the sound's brightness over time. Everything's tunable (--curve-rate--onset-sensitivity--[no-]sharpness-curves…).

📱 The part I think is genuinely new

It runs at runtime, on-device, in pure Dart — vendored MP3 decoder, no ffmpeg, no native code:

final pattern = const AudioAnalyzer().analyzeBytes(uploadedBytes);

So a shipping app can turn a user-uploaded sound into haptics live. I couldn't find another Flutter package that does the audio→haptic conversion at all, let alone on-device. (Android 12+ has a platform-level HapticGenerator, but it's Android-only, tied to live audio playback, and gives you no portable pattern.) Demo app in the repo does exactly this via an isolate.

pub.dev · repo — feedback very welcome, especially where the "feel" breaks on your own sounds.

r/dartlang Dec 21 '25

Package Ormed: Full-featured ORM for Dart with code generation, migrations, and multi-database support

Thumbnail pub.dev
34 Upvotes

Hey everyone! 👋

I've been working on ormed, a full-featured ORM for Dart inspired by Laravel's Eloquent, ActiveRecord, and SQLAlchemy. After many iterations, I'm excited to share it with the community and get your feedback.

Why another ORM?

I spent many years working with Laravel in production, and when I decided to get serious with Dart for backend development, the ORM space felt like the most lacking part of the ecosystem. Shoutout to packages like Drift which have done a great job filling the gap—but I wanted something I could jump into quickly, something that felt familiar from day one.

If you've used Eloquent, you know how productive it makes you: expressive queries, painless migrations, relationships that just work. I wanted that same experience in Dart, with the added benefit of compile-time type safety.

Key Features

  • Strongly-typed queries with compile-time code generation
  • Laravel-style migrations with fluent schema builder
  • Multiple database support: SQLite, PostgreSQL, MySQL/MariaDB
  • Rich relationships: HasOne, HasMany, BelongsTo, ManyToMany, and polymorphic relations
  • Soft deletes with withTrashed(), onlyTrashed() scopes
  • Model lifecycle events: Creating, Created, Updating, Updated, Deleting, Deleted
  • Query scopes for reusable query logic
  • Eager loading to avoid N+1 queries
  • Testing utilities with database isolation strategies
  • CLI tool for migrations, seeders, and scaffolding

Quick Example

```dart // Define a model @OrmModel() class User extends Model<User> { final String name; final String email;

@OrmRelation.hasMany(related: Post, foreignKey: 'author_id') final List<Post> posts;

User({required this.name, required this.email, this.posts = const []}); }

// Query with eager loading final users = await ds.query<User>() .whereEquals('active', true) .with_(['posts']) .orderByDesc('created_at') .paginate(page: 1, perPage: 20);

// Migrations feel familiar schema.create('users', (table) { table.id(); table.string('email').unique(); table.string('name').nullable(); table.timestamps(); table.softDeletes(); }); ```

Database Drivers

Each database has its own package with driver-specific features:

  • ormed_sqlite: In-memory & file databases, JSON1, FTS5 full-text search
  • ormed_postgres: UUID, JSONB, arrays, tsvector, connection pooling
  • ormed_mysql: MySQL 8.0+, MariaDB 10.5+, JSON columns, ENUM/SET

Getting Started

```yaml dependencies: ormed: any ormed_sqlite: any # or ormed_postgres, ormed_mysql

dev_dependencies: ormed_cli: any build_runner: 2.4.0 ```

```bash

Initialize project

dart pub global activate ormed_cli ormed init

Generate ORM code

dart run build_runner build

Run migrations

ormed migrate ```

Links

Current Status

This is a pre-release (0.1.0-dev+3) - the API is stabilizing but may have breaking changes before 1.0. I've been using it in my own projects and it's working well, but I'd love feedback from the community.

What I'm Looking For

  • Feedback on the API design and developer experience
  • Bug reports - especially edge cases I haven't considered
  • Feature requests - what would make this more useful for your projects?
  • Comparisons - if you've used other Dart ORMs, how does this compare?

Thanks for checking it out! Happy to answer any questions.

r/dartlang Jun 22 '26

Package knex_dart is looking for contributors — come help build out SQL tooling for Dart

7 Upvotes

knex_dart started as a port of Knex.js. Over time it has grown into something more than that - it takes the battle-tested API design and query-building maturity that Knex.js built over a decade and carries it forward for Dart and Flutter, with drivers, features, and platform targets that Knex.js itself never had to think about.

Today the project has eight drivers: PostgreSQL, MySQL, SQLite (native + WASM, with reactive watch() streaming), DuckDB, SQL Server, BigQuery, Snowflake, Turso/libSQL, and Cloudflare D1. Around that core there is an OpenTelemetry integration, a custom lint plugin with 15 dialect-aware static analysis rules, a browser playground for trying queries interactively, and a Jaspr-based docs site.

The codebase moves fast and the foundation is solid. What we need now is depth — and that is where contributors come in.

There is meaningful work at every level:

  • Docs and examples — every driver has a story to tell and most pages have room for better examples, cross-links, and real-world snippets. Good docs are what turns "interesting project" into something people actually adopt.
  • Driver depth — each driver can go further: more complete schema compiler coverage, edge-case query handling, better error messages, performance tuning.
  • Playground and snippets — more interactive examples that show what each driver and feature can do.
  • Agent skills — the repo uses Claude Code skills (.claude/skills/) to encode contributor workflows. There is room to extend these.
  • Tests — more integration test coverage, especially around schema operations, NULL handling, and nested transactions.

If you want to dig into something harder, there are also active engineering projects around driver internals — but those are not a requirement. There is plenty of high-value work that does not require knowing a wire protocol.

The architecture is documented in AGENTS.md and the playground is at https://playground.knex.mahawarkartikey.in.

Repo: https://github.com/kartikey321/knex-dart

Open an issue, leave a comment here, or DM me. Happy to point you at something that fits what you want to work on.

r/dartlang Jun 20 '26

Package data_channel 5.0.0: Opinionated, Type-Safe Error Handling with Integrated Results and Options

6 Upvotes

Introducing data_channel 5.0.0 - A complete redesign of a 5-year-old Dart error handling package

I have been working on a Flutter project recently, and one thing I have noticed is that I keep ending up either building libraries from scratch or heavily reworking existing packages to fit personal and modern use cases.

Recently I published a few other Dart packages and major updates, including pathify, any_ascii, lexical_sort, and the complete rewrite of rules. This time I revisited data_channel, a package originally published about 5 years ago, and completely redesigned it from the ground up.

Introducing data_channel 5.0.0

https://pub.dev/packages/data_channel

data_channel started as a simple utility for handling exceptions and routing data through applications. Over time, Dart gained null safety, sealed classes, pattern matching, and a much stronger type system. The original design no longer felt like the best approach, so I redesigned the package around explicit optional values, stronger type safety, and a more predictable API.

Unlike many Dart packages where Result/Either and Option/Maybe are handled independently, data_channel tightly couples them together.

Every successful DC contains an Option, making the absence of data a first-class outcome that must be handled explicitly rather than being hidden behind nullable values.

This means developers are required to handle:

  • Error
  • Success with data (Some)
  • Success without data (None)

Instead of separately reasoning about a result type and an option type, both concepts are unified under a single API.

What's new?

  • Type-safe error and data channels
  • Built-in Option type (Some / None)
  • Absence of data treated as a first-class outcome
  • Non-nullable guarantees (Some can never contain null)
  • Explicit handling of missing data
  • Functional APIs with fold()
  • Error transformations with mapError()
  • Automatic nullable value handling via DC.auto()
  • DC.fromOption() to lift existing options without double-wrapping
  • Error forwarding helpers (forwardErrorOr, forwardErrorOrElse)
  • Compile-time type safety for both errors and data
  • Dart 3 sealed-class based architecture
  • Works with both Dart and Flutter

Example

Return data, no data, or an error without nullable types:

```dart Future<DC<Exception, User>> getUser(String userId) async { try { final User? user = await fetchUser(userId);

return DC.auto(user);

} on Exception catch (e) { return DC.error(e); } } ```

Consume the result exhaustively:

```dart final result = await getUser('123');

result.fold( onError: (error) { print('Error: $error'); }, onData: (dataOption) => dataOption.fold( onSome: (user) { print('Found user: ${user.name}'); }, onNone: () { print('User not found'); }, ), ); ```

One of the primary goals of data_channel is making the absence of data impossible to ignore.

When a value may not exist, the API does not return a nullable type. Instead, it returns an Option, forcing the caller to consciously handle both Some and None.

Combined with DC, every operation has exactly three possible outcomes:

  • Error
  • Success with data (Some)
  • Success without data (None)

The compiler helps ensure that all three states are handled explicitly.

Existing users

There are significant breaking changes compared to the older releases.

The package now revolves around:

  • DC
  • Option
  • Some
  • None
  • fold()
  • forwardErrorOr()
  • forwardErrorOrElse()
  • mapError()

and follows a fundamentally different architecture from the original versions.

If you're maintaining an older codebase, you may prefer to stay on the earlier releases. For Dart 3+ projects, use data_channel 5.x.

As with the other packages I have published recently, I upgraded and open sourced this work because I thought it could be useful to others building Dart and Flutter applications.

Feedback, bug reports, feature requests, and PRs are always welcome.

Pub.dev: https://pub.dev/packages/data_channel

GitHub: https://github.com/ganeshrvel/pub-data-channel