Kill Magic Numbers in Dart: Named Constants Guide

Bare literals are ticking time bombs. This Dart/Flutter example walks the magic number code smell from diagnosis to named constants, enums, and analyzer enforcement.

Last updated: 2026-10-08 A bare 3.14 in your code. A timeout: 30 in a retry loop. Six months later you change one and break three — because you couldn&#x27;t find the others. That is the magic number code smell , and this magic number code smell Dart Flutter example shows you every place it hides — layout padding, HTTP retries, status codes — and the exact fix. No theory first. The fix first, the reasoning second. What the bug looks like: magic number code smell (dart flutter example) Your code compiles. Your app runs. Nothing is "broken" — which is exactly why this smell survives code review. It looks like this: // ❌ Magic numbers everywhere Future<Order> fetchOrder(String id) async { final response = await _client .get(Uri.parse(&#x27;$_baseUrl/orders/$id&#x27;)) .timeout(const Duration(seconds: 30)); if (response.statusCode == 200) { return Order.fromJson(jsonDecode(response.body)); } if (response.statusCode == 429) { await Future.delayed(const Duration(seconds: 60)); return fetchOrder(id); // retry once } throw Exception(&#x27;Request failed: ${response.statusCode}&#x27;); } And this, in a Flutter widget: // ❌ Layout magic numbers Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), child: Column( children: [ const SizedBox(height: 24), Text(title, style: const TextStyle(fontSize: 20)), const SizedBox(height: 8), ElevatedButton( style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 14), ), onPressed: onSubmit, child: const Text(&#x27;Submit&#x27;), ), ], ), ) Read that widget in six months. Is 16 the same spacing as 32 ? Is 24 a "section gap" or a "card gap"? Is the 60 in the retry loop seconds, and should it match the 30 timeout? Nobody knows. The numbers have no names, so they have no meaning — and…

Explore