Skip to content
View on GitHub

Use the Geometry Editor to edit geometries using utility network connectivity rules.

Image of snapping

Use case

A field worker can create new features in a utility network by editing and snapping the vertices of a geometry to existing features on a map. In a gas utility network, gas pipeline features can be represented with the polyline geometry type. Utility networks use geometric coincident-based connectivity to provide pathways for resources. Rule-based snapping uses utility network connectivity rules when editing features based on their asset type and asset group to help maintain network connectivity.

How to use the sample

To edit a geometry, tap a point geometry to be edited in the map to select it. Then edit the geometry by tapping the button to start the geometry editor.

Snap sources can be enabled and disabled. Snapping will not occur when SnapRuleBehavior.rulesPreventSnapping even when the source is enabled.

To interactively snap a vertex to a feature or graphic, ensure that snapping is enabled for the relevant snap source, then move the reticle or drag a vertex to nearby an existing feature or graphic. If the existing feature or graphic has valid utility network connectivity rules for the asset type that is being created or edited, the edit position will be adjusted to coincide with (or snap to) edges and vertices of its geometry. Release the touch pointer to place the vertex at the snapped location.

To discard changes and stop the geometry editor, tap the discard button.

To save your edits, tap the save button.

How it works

  1. Create a map with LoadSettings.featureTilingMode set to enabledWithFullResolutionWhenSupported.

  2. Create a Geodatabase using the mobile geodatabase file location.

  3. Display Geodatabase.featureTables on the map using subtype feature layers.

  4. Create a GeometryEditor and connect it to the map view.

  5. When editing a feature:

    a. Call SnapRules.createFromAssetType() to get the snap rules associated with a given UtilityAssetType.

    b. Use syncSourceSettingsUsingRules(SnapRules, SnapSourceEnablingBehavior.setFromRules) to populate the SnapSettings.sourceSettings with SnapSourceSettings enabling the sources with rules.

  6. Start the geometry editor with an existing geometry or GeometryType.point.

Relevant API

  • ArcGISMapView
  • FeatureLayer
  • Geometry
  • GeometryEditor
  • GeometryEditorStyle
  • GraphicsOverlay
  • SnapRuleBehavior
  • SnapRules
  • SnapSettings
  • SnapSource
  • SnapSourceEnablingBehavior
  • SnapSourceSettings
  • UtilityNetwork

About the data

The Naperville gas network mobile geodatabase contains a utility network with a set of connectivity rules that can be used to perform geometry edits with rules based snapping.

Tags

edit, feature, geometry editor, graphics, layers, map, snapping, utility network

Sample Code

snap_geometry_edits_with_utility_network_rules.dart
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// Copyright 2025 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:arcgis_maps_sdk_flutter_samples/common/common.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:go_router/go_router.dart';

class SnapGeometryEditsWithUtilityNetworkRules extends StatefulWidget {
  const SnapGeometryEditsWithUtilityNetworkRules({super.key});

  @override
  State<SnapGeometryEditsWithUtilityNetworkRules> createState() =>
      _SnapGeometryEditsWithUtilityNetworkRulesState();
}

class _SnapGeometryEditsWithUtilityNetworkRulesState
    extends State<SnapGeometryEditsWithUtilityNetworkRules>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // The geodatabase containing the utility network data.
  Geodatabase? _geodatabase;
  // The utility network from the geodatabase.
  late UtilityNetwork _utilityNetwork;
  // A flag for when the map view is ready and controls can be used.
  var _ready = false;

  // The currently selected feature and element, if any.
  ArcGISFeature? _selectedFeature;
  UtilityElement? _selectedElement;
  // The Snap Sources of the selected item.
  var _snapSources = <SnapSourceItem>[];

  // A flag for whether there are outstanding edits.
  var _canUndo = false;
  StreamSubscription<bool>? _canUndoSubscription;

  // A flag for when the settings bottom sheet is visible.
  var _settingsVisible = false;

  @override
  void dispose() {
    // Release resources.
    _canUndoSubscription?.cancel().ignore();
    _geodatabase?.close();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          SafeArea(
            top: false,
            left: false,
            right: false,
            child: Column(
              children: [
                Expanded(
                  // Add a map view to the widget tree and set a controller.
                  child: ArcGISMapView(
                    controllerProvider: () => _mapViewController,
                    onMapViewReady: onMapViewReady,
                    onTap: _selectedElement != null ? null : onTap,
                  ),
                ),
                // A legend to explain the representation of the snapping rules.
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  child: Row(
                    children: [
                      Text(
                        'Snapping',
                        style: Theme.of(context).textTheme.labelMedium,
                      ),
                      const Spacer(),
                      const SnapSourceSwatch(
                        snapRuleBehavior: SnapRuleBehavior.none,
                      ),
                      Text(
                        'Allowed',
                        style: Theme.of(context).textTheme.labelMedium,
                      ),
                      const SnapSourceSwatch(
                        snapRuleBehavior: SnapRuleBehavior.rulesLimitSnapping,
                      ),
                      Text(
                        'Limited',
                        style: Theme.of(context).textTheme.labelMedium,
                      ),
                      const SnapSourceSwatch(
                        snapRuleBehavior: SnapRuleBehavior.rulesPreventSnapping,
                      ),
                      Text(
                        'Prevented',
                        style: Theme.of(context).textTheme.labelMedium,
                      ),
                    ],
                  ),
                ),
                Row(
                  children: [
                    // A button to discard edits.
                    IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: _selectedElement == null ? null : discardEdits,
                    ),
                    const Spacer(),
                    // A button to show the Settings bottom sheet.
                    ElevatedButton(
                      onPressed: _snapSources.isEmpty
                          ? null
                          : () => setState(() => _settingsVisible = true),
                      child: const Text('Settings'),
                    ),
                    const Spacer(),
                    // A button to save edits.
                    IconButton(
                      icon: const Icon(Icons.save),
                      onPressed: _canUndo ? saveEdits : null,
                    ),
                  ],
                ),
              ],
            ),
          ),
          // Display a progress indicator and prevent interaction until state is ready.
          LoadingIndicator(visible: !_ready),
          // Display a banner with instructions at the top.
          SafeArea(
            left: false,
            right: false,
            child: IgnorePointer(
              child: Container(
                padding: const EdgeInsets.all(10),
                color: Colors.white.withValues(alpha: 0.7),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _selectedElement == null
                          ? 'Tap a point feature to edit'
                          : 'Group: ${_selectedElement!.assetGroup.name}, Type: ${_selectedElement!.assetType.name}',
                      textAlign: TextAlign.center,
                      style: Theme.of(context).textTheme.labelMedium,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      // The Settings bottom sheet.
      bottomSheet: _settingsVisible ? buildSettings(context) : null,
    );
  }

  // The build method for the Settings bottom sheet.
  Widget buildSettings(BuildContext context) {
    return BottomSheetSettings(
      onCloseIconPressed: () => setState(() => _settingsVisible = false),
      // A widget for each snap source to control its enabled state.
      settingsWidgets: (context) => [
        Row(
          children: [
            Text(
              'Snap Sources',
              style: Theme.of(context).textTheme.titleMedium,
            ),
          ],
        ),
        ..._snapSources.map(
          (source) => SnapSourceWidget(snapSourceItem: source),
        ),
      ],
    );
  }

  Future<void> onMapViewReady() async {
    // Download the Naperville utility network geodatabase.
    final listPaths = GoRouter.of(context).state.extra! as List<String>;
    final geodatabaseFile = File(listPaths.first);

    // Configure the map, centered on Naperville, IL.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreetsNight);
    map.initialViewpoint = Viewpoint.fromCenter(
      ArcGISPoint(
        x: -9811055.1560284,
        y: 5131792.195025,
        spatialReference: SpatialReference.webMercator,
      ),
      scale: 10000,
    );
    map.loadSettings.featureTilingMode =
        FeatureTilingMode.enabledWithFullResolutionWhenSupported;
    _mapViewController.arcGISMap = map;

    // Add a GraphicsOverlay to be used as a snap source.
    final graphicsOverlay = GraphicsOverlay()
      ..id = 'Graphics'
      ..renderer = SimpleRenderer(
        symbol: SimpleLineSymbol(
          style: SimpleLineSymbolStyle.dash,
          color: Colors.grey,
          width: 3,
        ),
      );
    final geometry = Geometry.fromJsonString(
      '{"paths":[[[-9811826.6810284462,5132074.7700250093],[-9811786.4643617794,5132440.9533583419],[-9811384.2976951133,5132354.1700250087],[-9810372.5310284477,5132360.5200250093],[-9810353.4810284469,5132066.3033583425]]],"spatialReference":{"wkid":102100,"latestWkid":3857}}',
    );
    graphicsOverlay.graphics.add(Graphic(geometry: geometry));
    _mapViewController.graphicsOverlays.add(graphicsOverlay);

    // Load the geodatabase from the downloaded file.
    final geodatabase = Geodatabase.withFileUri(geodatabaseFile.uri);
    await geodatabase.load();
    if (geodatabase.utilityNetworks.isEmpty) {
      throw Exception('No utility networks found in geodatabase');
    }
    _utilityNetwork = geodatabase.utilityNetworks.first;
    await _utilityNetwork.load();

    // Create feature layers from the geodatabase tables.
    final pipeLayer = SubtypeFeatureLayer.withFeatureTable(
      geodatabase.getGeodatabaseFeatureTable(tableName: 'PipelineLine')!,
    );
    final deviceLayer = SubtypeFeatureLayer.withFeatureTable(
      geodatabase.getGeodatabaseFeatureTable(tableName: 'PipelineDevice')!,
    );
    final junctionLayer = SubtypeFeatureLayer.withFeatureTable(
      geodatabase.getGeodatabaseFeatureTable(tableName: 'PipelineJunction')!,
    );
    _geodatabase = geodatabase;

    // Add the layers to the map and load them.
    map.operationalLayers.addAll([pipeLayer, deviceLayer, junctionLayer]);
    await Future.wait(map.operationalLayers.map((layer) => layer.load()));

    // Hide unwanted pipe sublayers.
    for (final sublayer in pipeLayer.subtypeSublayers) {
      switch (sublayer.name) {
        case 'Distribution Pipe':
        case 'Service Pipe':
          sublayer.isVisible = true;
        default:
          sublayer.isVisible = false;
      }
    }

    // Hide unwanted device sublayers.
    for (final sublayer in deviceLayer.subtypeSublayers) {
      switch (sublayer.name) {
        case 'Excess Flow Valve':
        case 'Controllable Tee':
          sublayer.isVisible = true;
        default:
          sublayer.isVisible = false;
      }
    }

    // Create and configure the geometry editor.
    final geometryEditor = GeometryEditor()
      ..snapSettings.isEnabled = true
      ..snapSettings.isFeatureSnappingEnabled = true;
    final tool = ReticleVertexTool()..style.vertexTextSymbol = null;
    geometryEditor.tool = tool;
    // Track when the Geometry Editor has unsaved edits.
    _canUndoSubscription = geometryEditor.onCanUndoChanged.listen((canUndo) {
      setState(() => _canUndo = canUndo);
    });
    _mapViewController.geometryEditor = geometryEditor;

    // Set the ready state variable to true to enable the sample UI.
    setState(() => _ready = true);
  }

  Future<void> onTap(Offset localPosition) async {
    // Identify the tapped feature.
    final identifyLayersResults = await _mapViewController.identifyLayers(
      screenPoint: localPosition,
      tolerance: 12,
    );
    if (!mounted) return;

    // Look through the sublayer results for a point feature to edit.
    final pointFeatures = identifyLayersResults
        .expand((result) => result.sublayerResults)
        .expand((result) => result.geoElements)
        .whereType<ArcGISFeature>()
        .where((feature) => feature.geometry is ArcGISPoint);
    if (pointFeatures.isEmpty) return;

    // Select the first point feature found.
    final feature = pointFeatures.first;
    await selectFeature(feature);
  }

  // Clear any existing selection.
  void clearSelection() {
    if (_selectedFeature == null) return;

    final featureLayer = _selectedFeature!.featureTable?.layer as FeatureLayer?;
    if (featureLayer == null) return;

    featureLayer.clearSelection();
    featureLayer.resetFeaturesVisible();

    for (final snapSource in _snapSources) {
      snapSource.dispose();
    }

    setState(() {
      _snapSources = [];
      _selectedFeature = null;
      _selectedElement = null;
    });
  }

  // Select a feature and start editing its geometry.
  Future<void> selectFeature(ArcGISFeature feature) async {
    if (!_ready) return;

    clearSelection();

    final featureLayer = feature.featureTable?.layer as FeatureLayer?;
    if (featureLayer == null) return;

    // Select this feature in its layer and hide it.
    featureLayer.selectFeature(feature);
    featureLayer.setFeatureVisible(feature: feature, visible: false);

    // Start editing this feature in the Geometry Editor.
    final geometryEditor = _mapViewController.geometryEditor!;
    final utilityElement = _utilityNetwork.createElement(
      arcGISFeature: feature,
    );
    final geometry = feature.geometry!;
    geometryEditor.startWithGeometry(geometry);
    geometryEditor.selectVertex(partIndex: 0, vertexIndex: 0);

    // Use the feature's symbol for the editor's symbols.
    final symbol = (feature.featureTable as GeodatabaseFeatureTable?)
        ?.layerInfo
        ?.drawingInfo
        ?.renderer
        ?.symbolForFeature(feature: feature);
    geometryEditor.tool.style
      ..vertexSymbol = symbol
      ..feedbackVertexSymbol = symbol
      ..selectedVertexSymbol = symbol;

    // Center the map on the feature.
    _mapViewController.setViewpointCenter(geometry.extent.center).ignore();

    // Mark this feature as selected.
    setState(() {
      _selectedFeature = feature;
      _selectedElement = utilityElement;
    });

    // Get the snapping rules for this asset type.
    final snapRules = await SnapRules.createFromAssetType(
      utilityNetwork: _utilityNetwork,
      assetType: _selectedElement!.assetType,
    );

    // Configure the Geometry Editor's snapping settings to use these rules.
    geometryEditor.snapSettings.syncSourceSettingsUsingRules(
      snapRules,
      snapSourceEnablingBehavior: SnapSourceEnablingBehavior.setFromRules,
    );
    // Additionally, enable snapping to the graphics overlay.
    geometryEditor.snapSettings.sourceSettings
        .where((settings) => settings.source is GraphicsOverlay)
        .forEach((settings) => settings.isEnabled = true);

    // Find the snap sources that we want to control.
    final snapSources = <SnapSourceItem>[];
    for (final sourceSetting in geometryEditor.snapSettings.sourceSettings) {
      if (sourceSetting.source is GraphicsOverlay) {
        // Add the graphics overlay snap source.
        snapSources.add(SnapSourceItem(sourceSetting));
      } else if (sourceSetting.source is SubtypeFeatureLayer) {
        // Add particular pipe sublayers as snap sources.
        final layer = sourceSetting.source as SubtypeFeatureLayer;
        if (layer.featureTable?.tableName == 'PipelineLine') {
          for (final sublayer in sourceSetting.childSourceSettings) {
            if (sublayer.source is SubtypeSublayer) {
              final subtypeSublayer = sublayer.source as SubtypeSublayer;
              if (subtypeSublayer.name == 'Distribution Pipe') {
                snapSources.add(SnapSourceItem(sublayer));
              } else if (subtypeSublayer.name == 'Service Pipe') {
                snapSources.add(SnapSourceItem(sublayer));
              }
            }
          }
        }
      }
    }
    setState(() => _snapSources = snapSources);
  }

  // Stop the Geometry Editor and discard any changes made to the selected feature.
  void discardEdits() {
    if (!_ready) return;

    _mapViewController.geometryEditor!.stop();

    clearSelection();
  }

  // Stop the Geometry Editor and save changes made to the selected feature.
  void saveEdits() {
    if (!_ready) return;

    final geometry = _mapViewController.geometryEditor!.stop()!;
    _selectedFeature!.geometry = geometry;
    _selectedFeature!.featureTable!.updateFeature(_selectedFeature!).ignore();

    clearSelection();
  }
}

// A Snap Source that can be displayed and controlled.
class SnapSourceItem {
  // Create a Snap Source item from the given settings, applying a renderer based on the snapping rules.
  SnapSourceItem(this._snapSourceSettings) {
    // The renderer to apply based on the snapping rules behavior.
    final guideRenderer = ruleRenderers[_snapSourceSettings.ruleBehavior];

    // Determine the name of the source and store its original renderer.
    if (_snapSourceSettings.source is GraphicsOverlay) {
      final overlay = _snapSourceSettings.source as GraphicsOverlay;
      name = overlay.id;
      _originalRenderer = overlay.renderer;
      overlay.renderer = guideRenderer;
    } else if (_snapSourceSettings.source is SubtypeSublayer) {
      final sublayer = _snapSourceSettings.source as SubtypeSublayer;
      name = sublayer.name;
      _originalRenderer = sublayer.renderer;
      sublayer.renderer = guideRenderer;
    }

    // Listen for changes to the enabled state and update the settings.
    isEnabled.addListener(
      () => _snapSourceSettings.isEnabled = isEnabled.value,
    );
  }

  // Restore the original settings and dispose.
  void dispose() {
    if (_snapSourceSettings.source is GraphicsOverlay) {
      final overlay = _snapSourceSettings.source as GraphicsOverlay;
      overlay.renderer = _originalRenderer;
    } else if (_snapSourceSettings.source is SubtypeSublayer) {
      final sublayer = _snapSourceSettings.source as SubtypeSublayer;
      sublayer.renderer = _originalRenderer;
    }

    _snapSourceSettings.isEnabled = true;

    isEnabled.dispose();
  }

  // The Snap Source Settings being controlled.
  final SnapSourceSettings _snapSourceSettings;
  // The original renderer of the source, to be restored later.
  late final Renderer? _originalRenderer;

  // The name of the source.
  late final String name;
  // The enabled state of the snap source.
  final isEnabled = ValueNotifier<bool>(true);

  // Renderers to apply based on the snapping rules behavior.
  static final ruleRenderers = {
    SnapRuleBehavior.rulesPreventSnapping: SimpleRenderer(
      symbol: SimpleLineSymbol(color: Colors.red, width: 4),
    ),
    SnapRuleBehavior.rulesLimitSnapping: SimpleRenderer(
      symbol: SimpleLineSymbol(color: Colors.orange, width: 3),
    ),
    SnapRuleBehavior.none: SimpleRenderer(
      symbol: SimpleLineSymbol(
        style: SimpleLineSymbolStyle.dash,
        color: Colors.green,
        width: 3,
      ),
    ),
  };
}

// A widget to display and control a SnapSourceItem.
class SnapSourceWidget extends StatelessWidget {
  const SnapSourceWidget({required this.snapSourceItem, super.key});

  // The SnapSourceItem being controlled.
  final SnapSourceItem snapSourceItem;

  @override
  Widget build(BuildContext context) {
    // Listen to changes in the enabled state of the snap source.
    return ValueListenableBuilder(
      valueListenable: snapSourceItem.isEnabled,
      builder: (context, value, child) {
        return SwitchListTile(
          title: Text(snapSourceItem.name),
          value: value,
          // Toggle the enabled state of the snap source.
          onChanged: (value) => snapSourceItem.isEnabled.value = value,
        );
      },
    );
  }
}

// A widget to load and display a swatch for a given SnapRuleBehavior.
class SnapSourceSwatch extends StatefulWidget {
  const SnapSourceSwatch({required this.snapRuleBehavior, super.key});

  // The SnapRuleBehavior to display a swatch for.
  final SnapRuleBehavior snapRuleBehavior;

  @override
  State<SnapSourceSwatch> createState() => _SnapSourceSwatchState();
}

class _SnapSourceSwatchState extends State<SnapSourceSwatch> {
  // The width and height of the swatch image, in device-independent pixels.
  static const _dimension = 8.0;

  // A Completer that completes when the swatch image is ready.
  final _swatchCompleter = Completer<Uint8List>();

  @override
  void initState() {
    super.initState();

    SchedulerBinding.instance.addPostFrameCallback((_) {
      // Get the device pixel ratio after the first frame to ensure it is accurate.
      final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);

      // Create a swatch image using the renderer for the given SnapRuleBehavior.
      final renderer = SnapSourceItem.ruleRenderers[widget.snapRuleBehavior]!;
      renderer.symbol!
          .createSwatch(
            screenScale: devicePixelRatio,
            width: _dimension,
            height: _dimension,
          )
          .then((image) {
            // Signal that the swatch image is ready.
            _swatchCompleter.complete(image.getEncodedBuffer());
          })
          .ignore();
    });
  }

  @override
  Widget build(BuildContext context) {
    // Use a FutureBuilder to display the swatch image when it is ready.
    return FutureBuilder(
      future: _swatchCompleter.future,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          // The swatch image is ready -- display it.
          return Image.memory(snapshot.data!);
        }

        // Until the image is ready, reserve space to avoid layout changes.
        return const SizedBox(width: _dimension, height: _dimension);
      },
    );
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.