Defensive Dart: Validate User Input at Every Boundary

Learn how to validate user input in Dart the defensive way: boundary checks, safe parsing with tryParse, null-safety discipline, assert-vs-throw contracts, and malformed-JSON handling — with runnable Dart 3.10 examples.

Last updated: October 23, 2026 It always starts the same way: a crash report at 2 a.m. because one user typed "twelve" into an age field, or an API returned {"price": "N/A"} where your code assumed a number. To dart validate user input properly, the fix is never "add one more try-catch" — it's distrusting everything that crosses a boundary: stdin, text fields, JSON payloads, function arguments, even your own nullable fields. Six layers follow, from int.tryParse to assert-vs-throw contracts, each with runnable Dart 3.10 code. By the end, bad input will bounce off your program instead of exploding inside it. Six defensive layers: boundaries, parsing, JSON, nulls, contracts, exceptions. The 6 defensive layers you'll add Layer 1 — Validate at the boundary: stdin, function arguments, "validate at the edge, trust inside" Layer 2 — Parse, don't crash: int.tryParse and the retry loop for user-entered numbers Layer 3 — Survive malformed JSON: defensive fromJson with type checks and a Result type Layer 4 — Null-safety discipline: ?? , ?. , and early returns instead of the ! hammer Layer 5 — assert vs throw: which contract tool fits which situation (decision table included) Layer 6 — Exception strategy: custom validation exceptions, caught specifically, never swallowed 🎬 Watch: 🎬 Watch: getting user input in Dart with dart:io Watch John Elder read and parse user input in Dart with stdin.readLineSync() — the boundary where every validation story starts. 8:00 ⏱ 8:00 · John Elder (Codemy.com) — click to play inline, or watch on YouTube . dart validate user input: the boundary checklist A boundary is anywhere data enters from somewhere you don't control: the keyboard, a text field, an HTTP response, a file, even a public function's arguments. The defensive…

Explore