Skip to content
View on GitHub

Demonstrates the workflow of getting the network state and validating the topology of a utility network.

Image of validate utility network topology

Use case

Dirty areas are generated where edits to utility network features have not been evaluated against the network rules. Tracing across this area could result in an error or return inaccurate results. Validating the utility network updates the network topology with the edited feature data, maintaining consistency between the features and topology. Querying the network state allows you to determine if there are dirty areas or errors in a utility network, and if it supports network topology.

How to use the sample

Select features to make edits and then tap 'Apply' to send edits to the server.

  • Tap 'Get State' to check if validate is required or if tracing is available.
  • Tap 'Validate' to validate network topology and clear dirty areas.
  • Tap 'Trace' to run a trace.

How it works

  1. Create and load an ArcGISMap with a portal item for a web map.
  2. Load the UtilityNetwork from the web map and switch its ServiceGeodatabase to a new branch version.
  3. Add LabelDefinitions for the fields that will be updated on a feature edit.
  4. Add the UtilityNetwork.dirtyAreaTable to the map to visualize dirty areas or errors.
  5. Set a default starting location and trace parameters to stop traversability on an open device.
  6. Get the UtilityNetworkCapabilities from the UtilityNetworkDefinition and use these values to enable or disable the 'Get State', 'Validate', and 'Trace' buttons.
  7. When an ArcGISFeature is selected for editing, populate the choice list for the field value using the field's CodedValueDomain.codedValues.
  8. When 'Apply' is tapped, update the value of the selected feature's attribute value with the selected CodedValue.code and call ServiceGeodatabase.applyEdits().
  9. When 'Get State' is tapped, call UtilityNetwork.getState() and print the results.
  10. When 'Validate' is tapped, get the current map extent and call UtilityNetwork.validateNetworkTopology(extent).
  11. When 'Trace' is tapped, call UtilityNetwork.trace(parameters) with the predefined parameters and select all features returned.
  12. When 'Clear' or 'Cancel' are tapped, clear all selected features on each layer in the map and close the attribute picker.

Relevant API

  • UtilityElement
  • UtilityElementTraceResult
  • UtilityNetwork
  • UtilityNetworkCapabilities
  • UtilityNetworkState
  • UtilityNetworkValidationJob
  • UtilityTraceConfiguration
  • UtilityTraceParameters
  • UtilityTraceResult

About the data

The Naperville electric feature service contains a utility network that can be used to query the network state and validate network topology before tracing. The Naperville electric webmap uses the same feature service endpoint and is shown in this sample. Authentication is required and handled within the sample code.

Additional information

Starting from 200.4, Advanced Editing extension is required for editing a utility network in following cases:

  • Stand-alone mobile geodatabase that is exported from ArcGIS Pro 2.7 or higher
  • Sync-enabled mobile geodatabase that is generated from an ArcGIS Enterprise Feature Service 11.2 or higher
  • Webmap or service geodatabase that points to an ArcGIS Enterprise Feature Service 11.2 or higher

Please refer to the "Advanced Editing" section in the extension license table in License and deployment for details.

Tags

dirty areas, edit, network topology, online, state, trace, utility network, validate

Sample Code

validate_utility_network_topology.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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// 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:math';

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

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

  @override
  State<ValidateUtilityNetworkTopology> createState() =>
      _ValidateUtilityNetworkTopologyState();
}

class _ValidateUtilityNetworkTopologyState
    extends State<ValidateUtilityNetworkTopology>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // The web map used in the sample.
  late ArcGISMap _map;
  // The utility network used in the sample.
  late UtilityNetwork _utilityNetwork;
  // The trace parameters to be used for performing traces.
  late UtilityTraceParameters _traceParameters;

  // Variables used for editing.
  // The name of the 'Electric Distribution Line' feature table.
  final _lineTableName = 'Electric Distribution Line';
  // The name of the 'Electric Distribution Device' feature table.
  final _deviceTableName = 'Electric Distribution Device';
  // The name of the device status field in the 'Electric Distribution Device' feature table.
  final _deviceStatusField = 'devicestatus';
  // The name of the nominal voltage field in the 'Electric Distribution Line' feature table.
  final _nominalVoltageField = 'nominalvoltage';

  // Capabilities of the utility network.
  var _utilityNetworkCanTrace = false;
  var _utilityNetworkCanGetState = false;
  var _utilityNetworkCanValidate = false;

  // The selected feature currently being edited.
  ArcGISFeature? _selectedFeature;

  // The feature's field currently being edited.
  Field? _currentField;

  // The coded values from the field's domain.
  var _codedValues = <CodedValue>[];

  // The selected field's coded value.
  CodedValue? _selectedCodedValue;

  // Text describing the current status of the utility network.
  var _statusTitle = 'Loading webmap...';
  var _statusDetail = '';

  // Flags to toggle when UI controls can be used.
  var _clearEnabled = false;
  var _attributePickerVisible = false;
  var _ready = false;

  @override
  void initState() {
    // Set up authentication for the sample server.
    // Note: Never hardcode login information in a production application.
    // This is done solely for the sake of the sample.
    ArcGISEnvironment
        .authenticationManager
        .arcGISAuthenticationChallengeHandler = TokenChallengeHandler(
      'editor01',
      'S7#i2LWmYH75',
    );
    super.initState();
  }

  @override
  void dispose() {
    // Remove the TokenChallengeHandler and erase any credentials that were generated.
    ArcGISEnvironment
            .authenticationManager
            .arcGISAuthenticationChallengeHandler =
        null;
    ArcGISEnvironment.authenticationManager.arcGISCredentialStore.removeAll();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        left: false,
        right: false,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  // Add a map view to the widget tree and set a controller.
                  child: ArcGISMapView(
                    controllerProvider: () => _mapViewController,
                    onMapViewReady: onMapViewReady,
                    onTap: onTap,
                  ),
                ),
                // Configure buttons to perform the actions of the sample.
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 5),
                  child: Wrap(
                    spacing: 10,
                    children: [
                      SizedBox(
                        width: 200,
                        child: ElevatedButton(
                          onPressed: _utilityNetworkCanGetState
                              ? getState
                              : null,
                          child: const Text('Get State'),
                        ),
                      ),
                      SizedBox(
                        width: 200,
                        child: ElevatedButton(
                          onPressed: _utilityNetworkCanValidate
                              ? validate
                              : null,
                          child: const Text('Validate'),
                        ),
                      ),
                      SizedBox(
                        width: 200,
                        child: ElevatedButton(
                          onPressed: _utilityNetworkCanTrace
                              ? performTrace
                              : null,
                          child: const Text('Trace'),
                        ),
                      ),
                      SizedBox(
                        width: 200,
                        child: ElevatedButton(
                          onPressed: _clearEnabled ? clearAndReset : null,
                          child: const Text('Clear'),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // Display the status information from the sample actions in the UI.
            Container(
              padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
              color: Colors.white.withValues(alpha: 0.95),
              child: Column(
                spacing: 10,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          _statusTitle,
                          textAlign: TextAlign.center,
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          _statusDetail,
                          textAlign: TextAlign.center,
                          style: Theme.of(context).textTheme.labelLarge,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            LoadingIndicator(visible: !_ready),
          ],
        ),
      ),
      // Configure the bottom sheet the display an attribute picker when required.
      bottomSheet: _attributePickerVisible ? buildAttributePicker() : null,
    );
  }

  Future<void> onMapViewReady() async {
    // Create a map using the portal item of a web map containing a utility network.
    final portal = Portal(
      Uri.parse('https://sampleserver7.arcgisonline.com/portal/sharing/rest'),
    );
    final portalItem = PortalItem.withPortalAndItemId(
      portal: portal,
      itemId: '6e3fc6db3d0b4e6589eb4097eb3e5b9b',
    );
    _map = ArcGISMap.withItem(portalItem);

    // Set an initial viewpoint on the map.
    _map.initialViewpoint = Viewpoint.fromTargetExtent(
      Envelope.fromXY(
        xMin: -9815489.0660101417,
        yMin: 5128463.4221229386,
        xMax: -9814625.2768726498,
        yMax: 5128968.4911854975,
        spatialReference: SpatialReference.webMercator,
      ),
    );

    // Load in persistent session mode (workaround for server caching issue):
    // https://support.esri.com/en-us/bug/asynchronous-validate-request-for-utility-network-servi-bug-000160443
    _map.loadSettings = LoadSettings()
      ..featureServiceSessionType = FeatureServiceSessionType.persistent;

    // Load the map.
    await _map.load();

    // Define labels on the map for visualizing attribute editing.
    defineLabelsForLayer(_deviceTableName, _deviceStatusField, Colors.indigo);
    defineLabelsForLayer(_lineTableName, _nominalVoltageField, Colors.red);

    // Configure the utility network and trace parameters.
    try {
      await configureUtilityNetwork();
    } on ArcGISException catch (e) {
      setState(() {
        _ready = true;
        _statusTitle = 'Failed to configure utility network.';
        _statusDetail = e.message;
      });
      return;
    }

    // Add the map to the map view.
    _mapViewController.arcGISMap = _map;

    // Set the ready state variable to true to enable the sample UI.
    setState(() {
      _ready = true;
      _statusTitle = 'Utility Network loaded';
      _statusDetail =
          "Tap on a feature to edit.\nTap 'Get State' to check if validating is necessary or if tracing is available.\nTap 'Trace' to run a trace.";
    });
  }

  Future<void> configureUtilityNetwork() async {
    setState(() => _statusTitle = 'Loading utility network...');

    // Get the utility network from the map and load.
    _utilityNetwork = _map.utilityNetworks.first;
    await _utilityNetwork.load();

    // Get the service geodatabase.
    final serviceGeodatabase = _utilityNetwork.serviceGeodatabase!;
    // Restrict editing and tracing to a unique branch.
    final parameters = ServiceVersionParameters()
      ..name = 'ValidateNetworkTopology_${Guid()}'
      ..access = VersionAccess.private
      ..description = 'Validate network topology with ArcGIS Maps SDK';
    final serviceVersionInfo = await serviceGeodatabase.createVersion(
      newVersion: parameters,
    );
    await serviceGeodatabase.switchVersion(
      versionName: serviceVersionInfo.name,
    );

    // Add the dirty area table to the map to visualize it.
    final dirtyAreaTable = _utilityNetwork.dirtyAreaTable;
    if (dirtyAreaTable != null) {
      final featureLayer = FeatureLayer.withFeatureTable(dirtyAreaTable);
      _map.operationalLayers.add(featureLayer);
    }

    // Get the initial capabilities of the utility network.
    setState(() {
      _utilityNetworkCanTrace =
          _utilityNetwork.definition!.capabilities.supportsTrace;
      _utilityNetworkCanGetState =
          _utilityNetwork.definition!.capabilities.supportsNetworkState;
      _utilityNetworkCanValidate = _utilityNetwork
          .definition!
          .capabilities
          .supportsValidateNetworkTopology;
    });

    // Trace with a subnetwork controller as the default starting location.
    final networkSource = _utilityNetwork.definition!.getNetworkSource(
      _deviceTableName,
    );
    final assetGroup = networkSource!.getAssetGroup('Circuit Breaker');
    final assetType = assetGroup!.getAssetType('Three Phase');
    final startingLocation = _utilityNetwork.createElementWithAssetType(
      assetType!,
      globalId: Guid.fromString('{1CAF7740-0BF4-4113-8DB2-654E18800028}')!,
    );
    // Set the terminal for the location, in our case, the 'Load' terminal.
    final terminal = startingLocation.assetType.terminalConfiguration?.terminals
        .firstWhere((terminal) => terminal.name == 'Load');
    startingLocation.terminal = terminal;

    // Add a graphic to indicate the starting location on the map.
    final features = await _utilityNetwork.getFeaturesForElements([
      startingLocation,
    ]);
    final feature = features.first;
    await feature.load();
    final graphic = Graphic(
      geometry: feature.geometry,
      symbol: SimpleMarkerSymbol(
        style: SimpleMarkerSymbolStyle.cross,
        color: Colors.lightGreen,
        size: 25,
      ),
    );
    final graphicsOverlay = GraphicsOverlay()..graphics.add(graphic);
    _mapViewController.graphicsOverlays.add(graphicsOverlay);

    // Set the configuration to stop traversing on an open device.
    final sourceTier = _utilityNetwork.definition!
        .getDomainNetwork('ElectricDistribution')!
        .getTier('Medium Voltage Radial')!;
    _traceParameters = UtilityTraceParameters(
      UtilityTraceType.downstream,
      startingLocations: [startingLocation],
    )..traceConfiguration = sourceTier.getDefaultTraceConfiguration();
  }

  Future<void> onTap(Offset tappedLocation) async {
    setState(() {
      _ready = false;
      _statusTitle = 'Identifying feature to edit...';
      _statusDetail = '';
    });

    // Clear previous selection.
    clearSelectionsFromAllLayers();

    // Perform an identify to determine if a user tapped on a feature.
    final identifyResults = await _mapViewController.identifyLayers(
      screenPoint: tappedLocation,
      tolerance: 5,
    );

    if (identifyResults.isEmpty) {
      setNoFeatureIdentifiedStatus();
      return;
    }

    // Check for a result in the specified tables.
    final identifyLayerResult = identifyResults
        .where(
          (result) =>
              result.layerContent.name == _deviceTableName ||
              result.layerContent.name == _lineTableName,
        )
        .firstOrNull;

    if (identifyLayerResult == null ||
        identifyLayerResult.geoElements.isEmpty) {
      setNoFeatureIdentifiedStatus();
      return;
    }

    // Get the first feature from the results.
    final feature = identifyLayerResult.geoElements.first as ArcGISFeature;
    await feature.load();
    // Get the coded values from the feature's field.
    final fieldName = feature.featureTable!.tableName == _deviceTableName
        ? _deviceStatusField
        : _nominalVoltageField;
    final field = feature.featureTable!.getField(fieldName: fieldName);
    final codedValues = (field!.domain! as CodedValueDomain).codedValues;
    // If there are valid coded values, set them to the attribute picker values.
    if (codedValues.isEmpty) {
      setNoFeatureIdentifiedStatus();
      return;
    }
    // Select the feature on the map.
    if (feature.featureTable!.layer is FeatureLayer) {
      final featureLayer = feature.featureTable!.layer! as FeatureLayer;
      featureLayer.selectFeature(feature);
    }
    // Get the current field value and convert to coded value.
    final currentFieldValue = feature.attributes[field.name];
    final selectedCodedValue = codedValues.firstWhere(
      (value) => value.code == currentFieldValue,
    );
    // Configure the UI ready for feature editing.
    setState(() {
      _codedValues = codedValues;
      _selectedCodedValue = selectedCodedValue;
      _currentField = field;
      _selectedFeature = feature;
      _statusTitle = "Select a new '${field.alias}'.";
      _statusDetail = '';
      _clearEnabled = true;
      _attributePickerVisible = true;
      _ready = true;
    });
  }

  Future<void> getState() async {
    setState(() {
      _ready = false;
      _statusTitle = 'Getting utility network state...';
      _statusDetail = '';
    });

    // Get the current state from the utility network.
    final state = await _utilityNetwork.getState();
    var status =
        'Has Dirty Areas: ${state.hasDirtyAreas}\nHas Errors: ${state.hasErrors}\nIs Network Topology Enabled: ${state.isNetworkTopologyEnabled}';
    if (state.hasDirtyAreas || state.hasErrors) {
      status = "$status\nTap 'Validate' before trace or expect a trace error.";
    } else {
      status =
          "$status\nTap on a feature to edit or tap 'Trace' to run a trace.";
    }

    // Update the UI with the outcomes of the state check.
    setState(() {
      _utilityNetworkCanValidate = state.hasDirtyAreas || state.hasErrors;
      _utilityNetworkCanTrace = state.isNetworkTopologyEnabled;
      _statusTitle = 'Utility Network State:';
      _statusDetail = status;
      _ready = true;
    });
  }

  Future<void> validate() async {
    setState(() {
      _ready = false;
      _statusTitle = 'Validating utility network topology...';
      _statusDetail = '';
    });
    // Get the current extent of the map view.
    final extent = _mapViewController
        .getCurrentViewpoint(ViewpointType.boundingGeometry)!
        .targetGeometry
        .extent;

    // Validate the network topology at the current extent and get the result.
    final job = _utilityNetwork.validateNetworkTopology(extent: extent);
    final result = await job.run();

    // Update the UI with the validation result.
    setState(() {
      _statusTitle = 'Utility Validation Result:';
      _statusDetail =
          "Has Dirty Areas: ${result.hasDirtyAreas}\nHas Errors: ${result.hasErrors}\nTap 'Get State' to check the updated network state.";
      _utilityNetworkCanValidate = result.hasDirtyAreas;
      _ready = true;
    });
  }

  Future<void> performTrace() async {
    setState(() {
      _ready = false;
      _statusTitle = 'Running a downstream trace...';
      _statusDetail = '';
    });

    // Clear previous selection from the layers.
    clearSelectionsFromAllLayers();

    // Get the trace result from the utility network.
    try {
      final traceResult = await _utilityNetwork.trace(_traceParameters);
      final elementTraceResult = traceResult
          .whereType<UtilityElementTraceResult>()
          .firstOrNull;
      final elementsCount = elementTraceResult?.elements.length ?? 0;

      // Select any identified elements in the map.
      if (elementTraceResult != null) {
        for (final layer
            in _mapViewController.arcGISMap!.operationalLayers
                .whereType<FeatureLayer>()) {
          final elements = elementTraceResult.elements
              .where(
                (element) =>
                    element.networkSource.featureTable == layer.featureTable,
              )
              .toList();
          final features = await _utilityNetwork.getFeaturesForElements(
            elements,
          );
          layer.selectFeatures(features);
        }
      }
      // Update the state with the trace results.
      setState(() {
        _statusTitle = 'Trace completed:';
        _statusDetail = '$elementsCount elements found';
        _clearEnabled = true;
        _ready = true;
      });
    } on ArcGISException catch (e) {
      // If the trace fails update the status.
      showMessageDialog(e.additionalMessage, title: e.message, showOK: true);
      setState(() {
        _statusTitle = 'Trace failed:';
        _statusDetail = "Tap 'Get State' to check the updated network state.";
        _clearEnabled = false;
        _ready = true;
      });
    }
  }

  Future<void> applyEdits() async {
    if (_selectedFeature == null || _selectedCodedValue == null) return;
    // Get the service geodatabase and field name of the feature being edited.
    final table = _selectedFeature!.featureTable as ServiceFeatureTable?;
    if (table == null || table.serviceGeodatabase == null) return;
    final serviceGeodatabase = table.serviceGeodatabase!;
    final fieldName = _currentField?.name;
    if (fieldName == null) return;
    setState(() {
      _statusTitle = 'Updating feature...';
      _statusDetail = '';
      _ready = false;
    });
    // Set the selected value to the feature.
    _selectedFeature!.attributes[fieldName] = _selectedCodedValue!.code;
    await table.updateFeature(_selectedFeature!);
    setState(() {
      _statusTitle = 'Applying edits...';
      _statusDetail = '';
    });
    // Apply the edits to the service geodatabase.
    final editResult = await serviceGeodatabase.applyEdits();

    // Determine if the attempt to edit resulted in any errors.
    final hasErrors = editResult.any(
      (result) => result.editResults.any(
        (editResult) => editResult.completedWithErrors,
      ),
    );
    // Update the status with the results.
    var updatedStatusTitle = '';
    var updatedStatusDetail = '';
    if (!hasErrors) {
      updatedStatusTitle = 'Edits applied successfully.';
      updatedStatusDetail =
          "Tap 'Get State' to check the updated network state";
    } else {
      updatedStatusTitle = 'Edits completed with error.';
      updatedStatusDetail = '';
    }
    clearSelectionsFromAllLayers();
    setState(() {
      _utilityNetworkCanValidate = true;
      _statusTitle = updatedStatusTitle;
      _statusDetail = updatedStatusDetail;
      _attributePickerVisible = false;
      _clearEnabled = false;
      _ready = true;
    });
  }

  void clearSelectionsFromAllLayers() {
    _mapViewController.arcGISMap!.operationalLayers
        .whereType<FeatureLayer>()
        .forEach((layer) => layer.clearSelection());
  }

  void clearAndReset() {
    // Clear the selection.
    clearSelectionsFromAllLayers();
    // Make relevant UI updates.
    setState(() {
      _statusTitle = 'Selection cleared';
      _statusDetail = '';
      _attributePickerVisible = false;
      _selectedFeature = null;
      _clearEnabled = false;
    });
  }

  void setNoFeatureIdentifiedStatus() {
    setState(() {
      _statusTitle = 'No feature identified. Tap on a feature to edit.';
      _statusDetail = '';
      _attributePickerVisible = false;
      _clearEnabled = false;
      _ready = true;
    });
  }

  void defineLabelsForLayer(
    String layerName,
    String fieldName,
    MaterialColor color,
  ) {
    // Define a label definition based on the provided field name.
    final labelDefinition = LabelDefinition(
      labelExpression: SimpleLabelExpression(simpleExpression: '[$fieldName]'),
      textSymbol: TextSymbol(color: color, size: 12)
        ..haloColor = Colors.white
        ..haloWidth = 2,
    )..useCodedValues = true;

    // Add the label definition to the provided layer.
    final featureLayer = _map.operationalLayers
        .whereType<FeatureLayer>()
        .firstWhere((layer) => layer.name == layerName);
    featureLayer.labelDefinitions.add(labelDefinition);
    // Enable labels on the layer.
    featureLayer.labelsEnabled = true;
  }

  // The build method for the attribute picker bottom sheet.
  Widget buildAttributePicker() {
    return Container(
      padding: EdgeInsets.fromLTRB(
        20,
        20,
        20,
        max(
          20,
          View.of(context).viewPadding.bottom /
              View.of(context).devicePixelRatio,
        ),
      ),
      child: Column(
        spacing: 10,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            spacing: 10,
            children: [
              Text(
                'Edit Feature',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const Spacer(),
              // Add a button to apply the edits.
              ElevatedButton(onPressed: applyEdits, child: const Text('Apply')),
              // Add a button to cancel edits.
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  setState(() => _attributePickerVisible = false);
                  clearAndReset();
                },
              ),
            ],
          ),
          Row(
            children: [
              // Display the current field alias.
              Text(
                _currentField?.alias ?? 'Unknown field',
                style: Theme.of(context).textTheme.labelLarge,
              ),
            ],
          ),
          SizedBox(
            height: 200,
            // Display a list of coded values for the seleced feature.
            child: ListView.builder(
              itemCount: _codedValues.length,
              itemBuilder: (context, index) {
                final value = _codedValues[index];
                return ListTile(
                  // Update the selected value when an item is selected.
                  onTap: () => setState(() => _selectedCodedValue = value),
                  // Display the value's name.
                  title: Text(value.name),
                  // Display a check if the item is the currently selected coded value.
                  trailing: value == _selectedCodedValue
                      ? const Icon(Icons.check)
                      : null,
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

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