Lesson 0005 • Unit Search & Derived Providers

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.

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/:

  1. 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 2 before Page 10).
  2. 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 of useMemo / 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"]
Figure 5.1: Multi-token AND evaluation and 3-tier ranking in PartSearchEngine.

Block 1: EngineeringDimension & EngineeringValue

EngineeringDimension enum and tolerance-aware EngineeringValue in lib/search/part_search_engine.dart
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;
  }

Block 2: Parsing EE-Infix (4k7, 3v3) vs. Standard SI (0.1uF, 100nF)

parseEngineeringToken handling EE-infix notation and rejecting bare integers like '104'
    // 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;
      }
      // ...
    }

Interactive Simulator: Engineering Unit Normalization & 3-Tier Ranking

Click Any Query to Trace

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:

Natural alphanumeric slot comparator in PartSearchEngine
  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:

TypeScript discriminated union for filter chips
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 in lib/search/workbench_filter_provider.dart
@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:

Exhaustive Dart 3 switch expression with pattern destructuring and 'when' guard
  // 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(),
  };

Block 2: Derived Provider (filteredWorkbenchView vs. React's useMemo)

Derived filteredWorkbenchView provider combining catalogProvider, searchQueryProvider, and selectedFacetProvider
@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

3. Interactive Practice & Verification

Interactive Lab: Dart 3 Sealed Classes, Cascades & Derived Providers

Skill Practice • Tight Feedback Loop

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."

:::

Retrieval Practice: Engineering Unit Search, Sealed Classes & Derived State

3 Questions • Equal-Length Options
1. How does @freezed sealed class WorkbenchFacet compare to TypeScript discriminated unions?
2. Why does PartSearchEngine.parseEngineeringToken('104') return null instead of expanding to 100nF?
3. How does the derived @riverpod FilteredWorkbenchView filteredWorkbenchView(Ref ref) provider behave when searchQueryProvider changes?

Verification Lab: Run Engineering Search & Filter Provider Suite

CLI Gate • Zero Warnings & 100% Green

Run static analysis and the complete 9-test suite inside tutorial/apps/0005-engineering-unit-search-and-filter-providers:

Terminal verification commands for Lesson 0005
cd tutorial/apps/0005-engineering-unit-search-and-filter-providers
flutter analyze
flutter test

Expected terminal output:

Verified output of flutter analyze && flutter test
Analyzing 0005-engineering-unit-search-and-filter-providers...
No issues found!
00:01 +9: All tests passed!