This article was drafted with AI help and reviewed by the author.
A warehouse counter scans a carton of jam. The app adds 1. The carton holds 12 jars. The stock system now thinks 11 jars went missing, and the next count "finds" them again.
That bug has nothing to do with the scanner. It comes from treating a barcode as a SKU. In most catalogs one SKU has several barcodes, one per packaging level. The each has one, the inner pack may have one, and the case has its own. The app has to know which one it just read.
This post builds the core of a Flutter stock count screen around that idea. It covers barcode normalization, resolving a scan to a SKU and a unit of measure, counting in base units, and syncing to Supabase so a retry cannot count the same scan twice.
The pure Dart parts were checked with dart analyze and run against sample data with Dart 3.14 and the supabase 2.16 package. The Flutter widget at the end was not compiled, because no Flutter SDK was available. The SQL was not run against a live project. None of it is production-tested.
The problem
Three things go wrong in a typical first version.
- The case counts as one. The app maps every barcode straight to a SKU and adds 1.
-
The same product does not match. The item master stores
0614141000005. The scanner returns614141000005. A plain string lookup says "unknown item". - A retry doubles the count. The phone sends a batch, the connection drops before the response, and the app sends the batch again. The server now has every line twice.
Each one is cheap to prevent in the client, as long as the item master gives the app the right data.
What the item master must give the app
For every scannable barcode, the app needs three facts:
- the SKU it belongs to
- the unit of measure it represents, such as
EAorCS - how many base units (eaches) that one scan stands for
The conversion must come from the item master. Do not let the counter type "12 per case" on the floor. If the master is wrong, fix it there, so the WMS, the ERP and the app agree.
Normalize the scan to GTIN-14
GS1 recommends storing GTINs as 14 digits, right-justified and zero-filled. A GTIN-12 gets two leading zeros. A GTIN-13 gets one. So normalize both the item master and every scan to 14 digits before you compare them.
The last digit is a check digit. GS1 publishes the method. Multiply the digits by 3 and 1 alternately, starting from the digit just left of the check digit, add them up, and subtract from the next multiple of ten. Validating it catches misreads and a lot of typing errors when someone enters a code by hand.
```dart /// Returns the scan as a 14-digit GTIN, or null if it is not a valid GTIN. String? normalizeGtin(String raw) { final digits = raw.trim(); if (!RegExp(r'^\d+$').hasMatch(digits)) return null; if (![8, 12, 13, 14].contains(digits.length)) return null;
final gtin14 = digits.padLeft(14, '0'); return hasValidCheckDigit(gtin14) ? gtin14 : null; }
bool hasValidCheckDigit(String gtin14) { var sum = 0; // Walk right to left from the digit before the check digit. // Weights alternate 3, 1, 3, 1 ... for (var i = 0; i < 13; i++) { final digit = gtin14.codeUnitAt(12 - i) - 48; sum += digit * (i.isEven ? 3 : 1); } final expected = (10 - sum % 10) % 10; return expected == gtin14.codeUnitAt(13) - 48; } ```
Scans that are not GTINs, such as location labels or internal codes, return null. Handle those in a separate path. Do not let them fall through to a product lookup.
Resolve the scan to a SKU and a pack level
The item master is a map from GTIN-14 to a pack level. The constructor rejects bad data up front: invalid barcodes, missing conversions, and the same GTIN mapped twice. It is much easier to fix those when the app loads the master than when a counter is standing at a shelf.
A Dart 3 sealed class makes the three outcomes explicit. The switch in the next section has to handle all of them.
```dart import 'gtin.dart';
/// One scannable packaging level of a SKU. class PackLevel { const PackLevel({ required this.sku, required this.uom, required this.eachesPerUnit, });
final String sku; final String uom; // EA, IP, CS ... final int eachesPerUnit; }
sealed class ScanResult { const ScanResult(); }
class Resolved extends ScanResult { const Resolved(this.gtin, this.level); final String gtin; final PackLevel level; }
class NotAGtin extends ScanResult { const NotAGtin(this.raw); final String raw; }
class UnknownGtin extends ScanResult { const UnknownGtin(this.gtin); final String gtin; }
class ItemMaster { ItemMaster(Map<String, PackLevel> byBarcode) { for (final entry in byBarcode.entries) { final gtin = normalizeGtin(entry.key); if (gtin == null) { throw ArgumentError('Item master barcode ${entry.key} is not a valid GTIN'); } if (entry.value.eachesPerUnit <= 0) { throw ArgumentError('${entry.value.sku} ${entry.value.uom} has no conversion'); } if (byGtin.containsKey(gtin)) { throw ArgumentError('GTIN $gtin is mapped twice'); } byGtin[gtin] = entry.value; } }
final Map<String, PackLevel> _byGtin = {};
ScanResult resolve(String raw) { final gtin = normalizeGtin(raw); if (gtin == null) return NotAGtin(raw); final level = _byGtin[gtin]; return level == null ? UnknownGtin(gtin) : Resolved(gtin, level); } } ```
Count in base units, one line per scan
The session keeps one line per scan. Each line stores what was scanned, which pack level it was, the conversion used at that moment, and the result in eaches.
Keeping the conversion on the line matters. If someone later changes the case size from 12 to 10 in the item master, old counts still show what the counter actually saw.
Each line also gets a client-generated UUID. That id is what makes the sync safe to retry.
```dart import 'dart:math';
import 'item_master.dart';
class CountLine { CountLine({ required this.clientLineId, required this.sessionId, required this.locationCode, required this.gtin, required this.level, required this.unitsCounted, required this.countedAt, });
final String clientLineId; final String sessionId; final String locationCode; final String gtin; final PackLevel level; final int unitsCounted; final DateTime countedAt;
int get eaches => unitsCounted * level.eachesPerUnit;
Map<String, Object> toRow() => { 'clientlineid': clientLineId, 'countsessionid': sessionId, 'locationcode': locationCode, 'sku': level.sku, 'scannedgtin': gtin, 'scanneduom': level.uom, 'eachesperunit': level.eachesPerUnit, 'unitscounted': unitsCounted, 'eaches': eaches, 'counted_at': countedAt.toUtc().toIso8601String(), }; }
class CountSession { CountSession({ required this.master, required this.sessionId, required this.locationCode, });
final ItemMaster master; final String sessionId; final String locationCode; final List<CountLine> pending = [];
/// Adds a line, or returns an error message for the operator. String? addScan(String raw, {int units = 1}) { if (units <= 0) return 'Quantity must be at least 1';
switch (master.resolve(raw)) { case NotAGtin(:final raw): return 'Not a product barcode: $raw'; case UnknownGtin(:final gtin): return 'Unknown barcode $gtin. Set this item aside and report it.'; case Resolved(:final gtin, :final level): pending.add(CountLine( clientLineId: newUuidV4(), sessionId: sessionId, locationCode: locationCode, gtin: gtin, level: level, unitsCounted: units, countedAt: DateTime.now(), )); return null; } }
Map<String, int> eachesBySku() { final totals = <String, int>{}; for (final line in pending) { totals.update(line.level.sku, (v) => v + line.eaches, ifAbsent: () => line.eaches); } return totals; } }
String newUuidV4() { final rnd = Random.secure(); final b = List<int>.generate(16, (_) => rnd.nextInt(256)); b[6] = (b[6] & 0x0f) | 0x40; b[8] = (b[8] & 0x3f) | 0x80; final hex = b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-' '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; } ```
An unknown barcode is not added as a guess. It returns a message the operator cannot miss. In the widget, pair it with haptic feedback or a sound. The counter should set the item aside, not keep scanning past it.
With sample data, one each scan plus one case scan with a quantity of 3 gives 37 eaches for the SKU, not 4.
Sync without double counting
On the server, the line id is the primary key. The Supabase Dart client supports upsert with onConflict and ignoreDuplicates. Official docs say that with ignoreDuplicates: true, rows that clash on the onConflict columns are ignored instead of merged. A resent batch becomes a no-op for the lines that already landed.
```dart import 'package:supabase/supabase.dart';
import 'count_session.dart';
/// Sends pending lines. Safe to call again after a timeout or crash. Future<void> pushCountLines(SupabaseClient client, CountSession session) async { if (session.pending.isEmpty) return;
final batch = List<CountLine>.of(session.pending); await client.from('stockcountlines').upsert( batch.map((line) => line.toRow()).toList(), onConflict: 'clientlineid', ignoreDuplicates: true, );
// Only forget lines after the server call returned without throwing. session.pending.removeWhere(batch.contains); } ```
The table enforces the rules again on the server. A check constraint makes sure the stored eaches match the units and the conversion, so a buggy client cannot quietly send a wrong total.
```sql create table public.stockcountlines ( clientlineid uuid primary key, countsessionid uuid not null, locationcode text not null, sku text not null, scannedgtin char(14) not null, scanneduom text not null, eachesperunit integer not null check (eachesperunit > 0), unitscounted integer not null check (unitscounted > 0), eaches integer not null, countedat timestamptz not null, receivedat timestamptz not null default now(), constraint eachesmatch check (eaches = unitscounted * eachesper_unit) );
alter table public.stockcountlines enable row level security;
create policy "counters can insert lines" on public.stockcountlines for insert to authenticated with check (true);
create view public.stockcounttotals with (securityinvoker = true) as select countsessionid, locationcode, sku, sum(eaches) as eaches from public.stockcountlines group by countsessionid, location_code, sku; ```
The policy here is deliberately simple. In a real app, tie it to the counter's user id or warehouse. security_invoker makes the view respect the caller's row level security instead of the view owner's. Test both with a real counter account before rollout.
Totals are always derived from lines. The app never sends "SKU X is now 37". That keeps the count auditable and keeps retries harmless.
A minimal scan field
Many rugged Android devices and Bluetooth scanners can act as a keyboard and send the code followed by Enter. Check your device settings. A focused TextField with onSubmitted is enough to receive those scans. Camera scanning can feed the same addScan() call.
```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart';
import 'count_session.dart';
class ScanField extends StatefulWidget { const ScanField({super.key, required this.session, required this.onChanged});
final CountSession session; final VoidCallback onChanged;
@override State<ScanField> createState() => _ScanFieldState(); }
class ScanFieldState extends State<ScanField> { final controller = TextEditingController(); final focus = FocusNode(); String? error;
@override void dispose() { controller.dispose(); focus.dispose(); super.dispose(); }
void submit(String value) { final error = widget.session.addScan(value); if (error != null) HapticFeedback.heavyImpact(); setState(() => error = error); controller.clear(); focus.requestFocus(); if (error == null) widget.onChanged(); }
@override Widget build(BuildContext context) { final last = widget.session.pending.isEmpty ? null : widget.session.pending.last; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextField( controller: controller, focusNode: focus, autofocus: true, onSubmitted: submit, decoration: InputDecoration( labelText: 'Scan barcode', errorText: error, ), ), if (last != null && _error == null) Text('${last.level.sku}: ${last.unitsCounted} ${last.level.uom} ' '= ${last.eaches} EA'), ], ); } } ```
Show the conversion on screen after every scan. "1 CS = 12 EA" right under the field is the fastest way for a counter to spot a wrong pack level.
Limitations
Pending lines live in memory in this sample. A real app must persist them locally before showing "saved", or a crash loses the count.
The GTIN code handles GTIN-8, 12, 13 and 14. It does not parse GS1-128 or DataMatrix element strings with lot, expiry or serial data. Those need a proper GS1 parser.
Kits and bundles are out of scope. Whether a kit is counted as one SKU or as its components is an item master decision, not an app decision.
The pure Dart code was analyzed and run locally. The widget was not compiled. The SQL and the policy were not run against a live Supabase project.
Takeaways
- A barcode identifies a pack level, not just a SKU.
- Normalize every GTIN to 14 digits and validate the check digit.
- Get the conversion from the item master, and store it on each count line.
- Count in eaches. Show the conversion after every scan.
- Reject unknown barcodes loudly. Never guess.
- Give each line a client UUID and upsert with
ignoreDuplicates, so retries are free. - Derive totals on the server from lines, never from a number the phone sends.
The app is only one piece. If you are wiring these counts back into a warehouse system, this WMS integration playbook goes through item master sync, order release and the stock flows around the app.
Top comments (0)