Engineering Unit Search Engine & Derived Filter Providers
Build PartSearchEngine (0.1uF == 100nF, 4k7 == 4.7kΩ, 3-tier ranking, natural slot sorting) and compose derived Riverpod selectors with Dart 3 @freezed sealed classes and pattern matching.
Why Electronics Search Needs More Than .includes()
When you're at a soldering workbench looking for a decoupling capacitor or pull-up resistor, your schematic might say 0.1uF or 4k7, while your catalog entry from LCSC is named 100nF 50V X7R 0603 Capacitor (C14663) or 4.7kΩ ±1% 0603 Resistor (C23162), or uses Greek Unicode characters like 10µF (U+00B5) or 10μF (U+03BC).
A naive part.name.toLowerCase().includes(query) check in JavaScript fails on all of these! Conversely, an overly aggressive parser that expands bare 3-digit EIA codes like "104" into 100nF and 100kΩ will produce noisy false positives whenever a user searches for an MPN substring or drawer number.
In this lesson, we build two tightly focused modules in ./tutorial/apps/0005-engineering-unit-search-and-filter-providers/:
PartSearchEngine(lib/search/part_search_engine.dart): Pure Dart unit normalization (EngineeringDimension,EngineeringValue), EE-infix parsing (4k7,3v3,2n2), Unicode folding (µ/μ→u,Ω/ohm→r), 3-tier relevance ranking, and natural alphanumeric slot sorting (Page 2beforePage 10).workbench_filter_provider.dart(lib/search/workbench_filter_provider.dart): A Dart 3@freezed sealed class WorkbenchFacet(our discriminated union for filter chips) and the derived@riverpod FilteredWorkbenchView filteredWorkbenchView(Ref ref)provider (Riverpod's dependency-tracked equivalent ofuseMemo/ Reselect).
1. Building PartSearchEngine (lib/search/part_search_engine.dart)
flowchart TD Query["Search Query: e.g. '0.1uF 50V' or '4700R'"] --> Split["Split into whitespace tokens<br/>(All tokens must match — AND semantics)"] Split --> T1["Tier 1: Exact prefix match on<br/>lcscCode (with or without 'C') or mpn"] T1 -->|No match| T2["Tier 2: Folded substring OR EngineeringValue<br/>equivalence in Part.name or Specs"] T2 -->|No match| T3["Tier 3: Folded substring in containerName,<br/>slot, package, category, manufacturer, or notes"] T3 -->|No match| Reject["Token unmatched → Part excluded"]
Block 1: EngineeringDimension & EngineeringValue
enum EngineeringDimension {
resistance,
capacitance,
inductance,
voltage,
current,
power,
frequency,
dimensionlessSi,
}
class EngineeringValue {
const EngineeringValue(this.dimension, this.baseValue);
final EngineeringDimension dimension;
final double baseValue;
bool matches(EngineeringValue other) {
final dimCompatible = _dimensionsCompatible(dimension, other.dimension);
if (!dimCompatible) return false;
final maxAbs = math.max(baseValue.abs(), other.baseValue.abs());
if (maxAbs == 0) return baseValue == other.baseValue;
return (baseValue - other.baseValue).abs() <= 1e-6 * maxAbs;
}- Why
1e-6 * maxAbsrelative tolerance? In IEEE-754 floating-point arithmetic,0.1 * 1e-6(0.1uF) and100 * 1e-9(100nF) can differ by1e-23due to binary representation. Comparing within1e-6relative tolerance matches0.1uF,100nF, and100000pFreliably (baseValue == 1.0e-7Farads). - Why
dimensionlessSi? When an engineer types a prefix-only shorthand like"100n","4.7k", or"4u7"without a trailingF,Ω, orH,_dimensionsCompatibleallowsdimensionlessSito match passive RLC dimensions (resistance,capacitance,inductance) of the same base magnitude without falsely matchingvoltage,current, orpower.
Block 2: Parsing EE-Infix (4k7, 3v3) vs. Standard SI (0.1uF, 100nF)
// 1. Check EE-infix notation: e.g. 4k7, 4K7, 4r7, 3v3, 2n2, 4u7, 1M5, 4k7R, 2n2F
final infixMatch = RegExp(
r'^(\d+)([pPnNuUmMkKgGrRvVfFhH])(\d+)([rRfFhHvVaAwW]|[hH][zZ])?$',
).firstMatch(normalizedRaw);
if (infixMatch != null) {
final intPart = infixMatch.group(1)!;
final marker = infixMatch.group(2)!;
final fracPart = infixMatch.group(3)!;
final trailingUnit = infixMatch.group(4)?.toLowerCase();
final mantissa = double.tryParse('$intPart.$fracPart');
if (mantissa == null) return null;
// ... resolves marker ('r' -> resistance, 'v' -> voltage, 'k' -> 1e3, etc.)
}
// 2. Check standard numeric + optional SI prefix + optional unit suffix:
// Must have AT LEAST a prefix OR a unit suffix (bare numbers like "104" are rejected!).
final stdMatch = RegExp(
r'^(\d+(?:\.\d+)?)([pPnNuUmMkKgG])?([hH][zZ]|[rRfFhHvVaAwW])?$',
).firstMatch(normalizedRaw);
if (stdMatch != null) {
final numStr = stdMatch.group(1)!;
final prefix = stdMatch.group(2);
final unit = stdMatch.group(3);
if (prefix == null && unit == null) {
return null;
}
// ...
}- Raw strings (
r'...'): Prefixing a Dart string literal withrcreates a raw string where backslashes\d,\s,\bare not interpreted as string escapes—so regular expressions look just like JS/^(\d+).../literals without double-escaping\\d! - Case-sensitive
'M'(1e6Mega) vs.'m'(1e-3milli): Notice that SI prefixes are case-insensitive (k/K,u/U,n/N) except'M'vs.'m'(1MΩ= $10^6,\Omega$,10mΩ= $10^{-2},\Omega$, whilemhzis treated as $10^6,\text{Hz}$). - Rejecting bare integers (
if (prefix == null && unit == null) return null;): Ensures"104"only matches literal substrings (like MPNCL10B104KB8NNNC) and never hallucinates100nFor100kΩ.
Select a workbench search query below to inspect how PartSearchEngine normalizes SI prefixes, EE-infix notation (4k7), and Unicode symbols (µ/Ω) into canonical base values:
Block 3: Natural Alphanumeric Slot Sorting (compareNaturalSlot)
In By Container mode, slots like "Page 2" and "Page 10" (or "A2" and "A10") should sort in human numerical order (Page 2 before Page 10), with null/empty bulk slots placed at the bottom of the container:
static int compareNaturalSlot(String? a, String? b) {
final aClean = a?.trim() ?? '';
final bClean = b?.trim() ?? '';
if (aClean.isEmpty && bClean.isEmpty) return 0;
if (aClean.isEmpty) return 1;
if (bClean.isEmpty) return -1;
final aChunks = _splitAlphaNumericChunks(aClean.toLowerCase());
final bChunks = _splitAlphaNumericChunks(bClean.toLowerCase());
final len = math.min(aChunks.length, bChunks.length);
for (var i = 0; i < len; i++) {
final ca = aChunks[i];
final cb = bChunks[i];
final aNum = int.tryParse(ca);
final bNum = int.tryParse(cb);
final int cmp;
if (aNum != null && bNum != null) {
cmp = aNum.compareTo(bNum);
} else {
cmp = ca.compareTo(cb);
}
if (cmp != 0) return cmp;
}
return aChunks.length.compareTo(bChunks.length);
}2. Derived Filter Providers & Sealed Classes (lib/search/workbench_filter_provider.dart)
Block 1: Discriminated Unions in Dart 3 (@freezed sealed class WorkbenchFacet)
In TypeScript, you model filter chip state as a discriminated union:
type WorkbenchFacet =
| { readonly kind: 'all' }
| { readonly kind: 'lowStock' }
| { readonly kind: 'unassigned' }
| { readonly kind: 'category'; readonly category: string };In Dart 3 + Freezed, you write a @freezed sealed class:
@freezed
sealed class WorkbenchFacet with _$WorkbenchFacet {
const factory WorkbenchFacet.all() = WorkbenchFacetAll;
const factory WorkbenchFacet.lowStock() = WorkbenchFacetLowStock;
const factory WorkbenchFacet.unassigned() = WorkbenchFacetUnassigned;
const factory WorkbenchFacet.category(String category) =
WorkbenchFacetCategory;
}And look at how you pattern-match on WorkbenchFacet inside filteredWorkbenchView:
// If the selected category facet no longer exists in the catalog, treat as All
final effectiveFacet = switch (selectedFacet) {
WorkbenchFacetCategory(:final category)
when !availableCategoriesSet.any(
(c) => c.toLowerCase() == category.toLowerCase(),
) =>
const WorkbenchFacet.all(),
_ => selectedFacet,
};
// Inside the parts loop:
final matchesFacet = switch (effectiveFacet) {
WorkbenchFacetAll() => true,
WorkbenchFacetLowStock() => part.isLowStock,
WorkbenchFacetUnassigned() => part.isUnassigned,
WorkbenchFacetCategory(:final category) =>
part.category != null &&
part.category!.toLowerCase() == category.toLowerCase(),
};- Exhaustiveness checking: Because
WorkbenchFacetis markedsealed, the Dart compiler knows every possible subtype (WorkbenchFacetAll,WorkbenchFacetLowStock,WorkbenchFacetUnassigned,WorkbenchFacetCategory). If you ever add a 5th facet constructor and forget to handle it inswitch (effectiveFacet),flutter analyzefails at compile time! WorkbenchFacetCategory(:final category) when ...: Extracts thecategoryproperty and applies a booleanwhenguard clause in a single declarative pattern.
Block 2: Derived Provider (filteredWorkbenchView vs. React's useMemo)
@riverpod
FilteredWorkbenchView filteredWorkbenchView(Ref ref) {
final asyncCatalog = ref.watch(catalogProvider);
final snapshot = asyncCatalog.value ?? CatalogSnapshot.empty();
final query = ref.watch(searchQueryProvider);
final selectedFacet = ref.watch(selectedFacetProvider);
// ... computes flatParts, containerGroups, availableCategories, and counts- No manual dependency arrays!In React,
useMemo(() => filterParts(parts, query, facet), [parts, query, facet])is prone to stale-closure bugs if a dependency is omitted. In Riverpod,ref.watch(...)dynamically tracks every upstream provider read during execution and caches theFilteredWorkbenchViewuntil one of those watched providers changes. - Dart's Cascade Operator (
..sort(...)):- Look at lines 114–115 of
workbench_filter_provider.dart:final availableCategories = availableCategoriesSet.toList() ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase())); - In JavaScript,
Array.prototype.sort()returns the sorted array, whereas in Dart,List.sort()returnsvoid(because it sorts in place). The cascade operator..invokes.sort(...)on the newly createdListand returns theListitself!
- Look at lines 114–115 of
3. Interactive Practice & Verification
Complete the missing Dart 3 pattern matching, cascade, and Riverpod tokens below:
@freezed
class WorkbenchFacet with _$WorkbenchFacet {
const factory WorkbenchFacet.all() = WorkbenchFacetAll;
const factory WorkbenchFacet.lowStock() = WorkbenchFacetLowStock;
const factory WorkbenchFacet.unassigned() = WorkbenchFacetUnassigned;
const factory WorkbenchFacet.category(String category) = WorkbenchFacetCategory;
}
// Exhaustive switch expression with pattern destructuring:
final matchesFacet = switch (effectiveFacet) {
WorkbenchFacetAll() => true,
WorkbenchFacetLowStock() => part.isLowStock,
WorkbenchFacetUnassigned() => part.isUnassigned,
WorkbenchFacetCategory() =>
part.category != null && part.category!.toLowerCase() == category.toLowerCase(),
};
// Sort a newly created list in-place and return the list using Dart's cascade operator:
final sortedContainers = [...snapshot.containers]
((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));:::prompts hint: "Closed union hierarchies use 'sealed class', property destructuring in patterns uses ':final category', and chaining a void method while returning the receiver uses the '..sort' cascade operator." success: "Nailed it! You can now combine @freezed sealed classes, Dart 3 pattern matching, cascade operators, and derived Riverpod providers."
:::
@freezed sealed class WorkbenchFacet compare to TypeScript discriminated unions?PartSearchEngine.parseEngineeringToken('104') return null instead of expanding to 100nF?@riverpod FilteredWorkbenchView filteredWorkbenchView(Ref ref) provider behave when searchQueryProvider changes?Run static analysis and the complete 9-test suite inside tutorial/apps/0005-engineering-unit-search-and-filter-providers:
cd tutorial/apps/0005-engineering-unit-search-and-filter-providers
flutter analyze
flutter testExpected terminal output:
Analyzing 0005-engineering-unit-search-and-filter-providers...
No issues found!
00:01 +9: All tests passed!