Manage features

View on GitHub

Create, update, and delete features to manage a feature layer.

Image of manage features

Use case

An end-user performing a survey may want to manage features on the map in various ways during the course of their work.

How to use the sample

Pick an operation, then tap on the map to perform the operation at that location. Available feature management operations include: "Create feature", "Delete feature", "Update attribute", and "Update geometry".

How it works

  1. Create a ServiceGeodatabase from a URL.
  2. Get a ServiceFeatureTable from the ServiceGeodatabase.
  3. Create a FeatureLayer derived from the ServiceFeatureTable instance.
  4. Apply the feature management operation upon tapping the map.
    • Create features: create a Feature with attributes and a location using the ServiceFeatureTable.
    • Delete features: delete the selected Feature from the FeatureTable.
    • Update attribute: update the attribute of the selected Feature.
    • Update geometry: update the geometry of the selected Feature.
  5. Update the FeatureTable locally.
  6. Update the ServiceGeodatabase of the ServiceFeatureTable by calling applyEdits().
    • This pushes the changes to the server.

Relevant API

  • Feature
  • FeatureEditResult
  • FeatureLayer
  • ServiceFeatureTable
  • ServiceGeodatabase

Additional information

When editing feature tables that are subject to database behavior (operations on one table affecting another table), it's now recommended to call these methods (apply or undo edits) on the ServiceGeodatabase object rather than on the ServiceFeatureTable object. Using the ServiceGeodatabase object to call these operations will prevent possible data inconsistencies and ensure transactional integrity so that all changes can be committed or rolled back.

Tags

amend, attribute, create, delete, deletion, details, edit, editing, feature, feature layer, feature table, geodatabase, information, moving, online service, service, update, updating, value

Sample Code

manage_features.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
// Copyright 2024 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 'package:arcgis_maps/arcgis_maps.dart';
import 'package:arcgis_maps_sdk_flutter_samples/utils/sample_state_support.dart';
import 'package:flutter/material.dart';

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

  @override
  State<ManageFeatures> createState() => _ManageFeaturesState();
}

class _ManageFeaturesState extends State<ManageFeatures>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();

  // Create a service feature table.
  late final ServiceFeatureTable _damageServiceFeatureTable;
  // Create a feature layer.
  late final FeatureLayer _damageFeatureLayer;

  // Create a list of feature management options.
  final _featureManagementOptions =
      <DropdownMenuItem<FeatureManagementOperation>>[];
  // Create a variable to store the selected operation.
  FeatureManagementOperation? _selectedOperation;

  // Create a list of damage type attribute options.
  final _damageTypeAttributeOptions = <DropdownMenuItem<String>>[];
  // Create a variable to store the attribute value of the selected damage type.
  String? _selectedDamageType;

  // Create a variable to store the selected feature.
  Feature? _selectedFeature;

  // A flag for when the map view is ready and controls can be used.
  var _ready = false;

  @override
  void initState() {
    super.initState();
    // Add each feature management operation to the list of dropdown menu options.
    _featureManagementOptions.addAll(
      FeatureManagementOperation.values.map(
        (operation) => DropdownMenuItem(
          onTap: () => setState(
            () => _selectedOperation == operation,
          ),
          value: operation,
          child: Text(getLabel(operation)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: 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,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(5),
                      child: Column(
                        children: [
                          // Create a dropdown button to select a feature management operation.
                          DropdownButton(
                            alignment: Alignment.center,
                            hint: const Text(
                              'Select operation',
                              style: TextStyle(color: Colors.deepPurple),
                            ),
                            value: _selectedOperation,
                            icon: const Icon(
                              Icons.arrow_drop_down,
                              color: Colors.deepPurple,
                            ),
                            elevation: 16,
                            style: const TextStyle(color: Colors.deepPurple),
                            // Set the onChanged callback to update the selected operation.
                            onChanged: (operation) =>
                                setState(() => _selectedOperation = operation),
                            items: _featureManagementOptions,
                          ),
                          // Display additional UI depending on the selected operation.
                          buildOperationSpecificWidget(),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: const SizedBox.expand(
                child: ColoredBox(
                  color: Colors.white30,
                  child: Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void onMapViewReady() async {
    try {
      // Create and load a service geodatabase from a service URL.
      const featureServiceUri =
          'https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0';
      final serviceGeodatabase =
          ServiceGeodatabase.withUri(Uri.parse(featureServiceUri));
      await serviceGeodatabase.load();

      // Get the feature table from the service geodatabase referencing the Damage Assessment feature service.
      // Creating the feature table from the feature service will cause the service geodatabase to be null.
      _damageServiceFeatureTable = serviceGeodatabase.getTable(layerId: 0)!;
      // Load the table.
      await _damageServiceFeatureTable.load();
      // Get the required field from the table - in this case, damage type.
      final damageTypeField = _damageServiceFeatureTable.fields
          .firstWhere((field) => field.name == 'typdamage');
      // Get the domain for the field.
      final domain = damageTypeField.domain! as CodedValueDomain;
      // Update the dropdown menu with the attribute values from the domain.
      configureAttributeDropdownMenuItems(domain);

      // Create a feature layer to visualize the features in the table.
      _damageFeatureLayer =
          FeatureLayer.withFeatureTable(_damageServiceFeatureTable);
      // Create a map with the ArcGIS Streets basemap.
      final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreets);
      // Add the feature layer to the map's operational layers.
      map.operationalLayers.add(_damageFeatureLayer);
      // Set the map to the map view controller.
      _mapViewController.arcGISMap = map;
      // Zoom to an initial viewpoint.
      _mapViewController.setViewpoint(
        Viewpoint.fromCenter(
          ArcGISPoint(
            x: -10800000,
            y: 4500000,
            spatialReference: SpatialReference.webMercator,
          ),
          scale: 3e7,
        ),
      );
      // Set the ready state variable to true to enable the sample UI.
      setState(() => _ready = true);
    } on ArcGISException catch (e) {
      showMessageDialog('${e.message}.');
    } on Exception {
      showMessageDialog(
        'There was an error loading the data required for the sample.',
      );
    }
  }

  void onTap(Offset localPosition) async {
    // Configure actions when a user taps on the map, depending on the selected operation.
    if (_selectedOperation == FeatureManagementOperation.create) {
      // Create a feature if create is selected.
      await createFeature(localPosition);
    } else if (_selectedOperation == FeatureManagementOperation.geometry &&
        _selectedFeature != null) {
      // If update geometry is selected, update the selected feature.
      await updateGeometry(_selectedFeature!, localPosition);
    } else {
      // Otherwise attempt to identify and select a feature.
      await identifyAndSelectFeature(localPosition);
    }
  }

  Future<void> identifyAndSelectFeature(Offset localPosition) async {
    // Disable the UI while the async operations are in progress.
    setState(() => _ready = false);

    // Unselect any previously selected feature.
    if (_selectedFeature != null) {
      _damageFeatureLayer.unselectFeature(_selectedFeature!);
      setState(() {
        _selectedFeature = null;
        _selectedDamageType = null;
      });
    }

    // Perform an identify operation on the feature layer at the tapped location.
    final identifyResult = await _mapViewController.identifyLayer(
      _damageFeatureLayer,
      screenPoint: localPosition,
      tolerance: 12.0,
      maximumResults: 1,
    );

    if (identifyResult.geoElements.isNotEmpty) {
      // If a feature is identified, select it.
      final feature = identifyResult.geoElements.first as ArcGISFeature;
      _damageFeatureLayer.selectFeature(feature);
      setState(() {
        _selectedFeature = feature;
        _selectedDamageType = feature.attributes['typdamage'];
      });
    }
    // Re-enable the UI.
    setState(() => _ready = true);
  }

  Future<void> createFeature(Offset localPosition) async {
    // Disable the UI while the async operations are in progress.
    setState(() => _ready = false);

    // Create the feature.
    final feature = _damageServiceFeatureTable.createFeature();

    // Get the normalized geometry for the tapped location and use it as the feature's geometry.
    final geometry = _mapViewController.screenToLocation(screen: localPosition);
    if (geometry != null) {
      final normalizedGeometry =
          GeometryEngine.normalizeCentralMeridian(geometry);
      feature.geometry = normalizedGeometry;

      // Set feature attributes.
      feature.attributes['typdamage'] = 'Minor';
      feature.attributes['primcause'] = 'Earthquake';

      // Add the feature to the local table.
      await _damageFeatureLayer.featureTable!.addFeature(feature);

      // Apply the edits to the service on the service geodatabase.
      await _damageServiceFeatureTable.serviceGeodatabase!.applyEdits();

      // Update the feature to get the updated objectid - a temporary ID is used before the feature is added.
      feature.refresh();

      // Confirm feature addition.
      showMessageDialog('Created feature ${feature.attributes['objectid']}');
    } else {
      showMessageDialog('Error creating feature, geometry was null.');
    }
    setState(() => _ready = true);
  }

  Future<void> deleteFeature(Feature feature) async {
    // Disable the UI while the async operations are in progress.
    setState(() => _ready = false);
    // Delete the feature from the local table.
    await _damageFeatureLayer.featureTable!.deleteFeature(feature);
    // Sync the change with the service on the service geodatabase.
    await _damageServiceFeatureTable.serviceGeodatabase!.applyEdits();
    showMessageDialog(
      'Deleted feature ${feature.attributes['objectid']}.',
    );
    // Reset selected elements and re-enable the UI.
    setState(() {
      _selectedFeature = null;
      _selectedDamageType = null;
      _ready = true;
    });
  }

  Future<void> updateGeometry(
    Feature feature,
    Offset localPosition,
  ) async {
    // Disable the UI while the async operations are in progress.
    setState(() => _ready = false);

    // Get the normalized geometry for the tapped location and use it as the feature's geometry.
    final newGeometry =
        _mapViewController.screenToLocation(screen: localPosition);
    if (newGeometry != null) {
      final normalizedNewGeometry =
          GeometryEngine.normalizeCentralMeridian(newGeometry);
      feature.geometry = normalizedNewGeometry;
      // Update the feature in the local table.
      await _damageFeatureLayer.featureTable!.updateFeature(feature);
      // Sync the change with the service on the service geodatabase.
      await _damageServiceFeatureTable.serviceGeodatabase!.applyEdits();
      showMessageDialog(
        'Updated feature ${feature.attributes['objectid']}',
      );
      // Re-enable the UI and deselect the currently selected feature.
      _damageFeatureLayer.unselectFeature(_selectedFeature!);
      setState(() {
        _selectedFeature = null;
        _ready = true;
      });
    }
  }

  void updateAttribute(Feature feature, String damageType) async {
    // Disable the UI while the async operations are in progress.
    setState(() => _ready = false);
    // Update the damage type field to the selected value.
    feature.attributes['typdamage'] = damageType;
    // Update the feature in the local table.
    await _damageFeatureLayer.featureTable!.updateFeature(feature);
    // Sync the change with the service on the service geodatabase.
    await _damageServiceFeatureTable.serviceGeodatabase!.applyEdits();
    showMessageDialog(
      'Updated feature ${feature.attributes['objectid']} to $damageType.',
    );
    // Re-enable the UI.
    setState(() => _ready = true);
  }

  void configureAttributeDropdownMenuItems(CodedValueDomain domain) {
    // Display a dropdown menu item for each coded value in the domain.
    _damageTypeAttributeOptions.addAll(
      domain.codedValues.map(
        (value) => DropdownMenuItem(
          onTap: () => setState(
            () => _selectedDamageType == value.name,
          ),
          value: value.name,
          child: Text(value.name),
        ),
      ),
    );
  }

  Widget buildOperationSpecificWidget() {
    switch (_selectedOperation) {
      case FeatureManagementOperation.create:
        // Display instructions for creating a new feature.
        return const Text('Tap on the map to create a feature.');
      case FeatureManagementOperation.delete:
        // Create a button to delete the selected feature.
        return ElevatedButton(
          onPressed: _selectedFeature != null
              ? () => deleteFeature(_selectedFeature!)
              : null,
          child: const Text('Delete Selected Feature'),
        );
      case FeatureManagementOperation.attribute:
        // Create a dropdown button for updating the attribute value of the selected feature.
        return DropdownButton(
          alignment: Alignment.center,
          hint: const Text(
            'Select attribute value',
            style: TextStyle(color: Colors.deepPurple),
          ),
          disabledHint: const Text(
            'Select a feature',
            style: TextStyle(
              color: Colors.grey,
            ),
          ),
          value: _selectedDamageType,
          icon: const Icon(Icons.arrow_drop_down),
          style: const TextStyle(color: Colors.deepPurple),
          iconEnabledColor: Colors.deepPurple,
          iconDisabledColor: Colors.grey,
          onChanged: _selectedFeature != null
              ? (String? damageType) {
                  if (damageType != null) {
                    setState(() => _selectedDamageType = damageType);
                    updateAttribute(_selectedFeature!, damageType);
                  }
                }
              : null,
          items: _damageTypeAttributeOptions,
        );
      case FeatureManagementOperation.geometry:
        // Display instructions for updating feature geometry.
        return const Text('Tap on the map to move a selected feature.');
      default:
        // Display default instructions.
        return const Text('Select a feature management operation.');
    }
  }

  String getLabel(FeatureManagementOperation operation) {
    // Return a UI friendly string for each feature management operation.
    switch (operation) {
      case FeatureManagementOperation.create:
        return 'Create feature';
      case FeatureManagementOperation.delete:
        return 'Delete feature';
      case FeatureManagementOperation.attribute:
        return 'Update attribute';
      case FeatureManagementOperation.geometry:
        return 'Update geometry';
      default:
        return 'Select a feature management operation.';
    }
  }

  void showMessageDialog(String message) {
    // Show a dialog with the provided message.
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text(message),
        );
      },
    );
  }
}

// Create an enumeration to define the feature management options.
enum FeatureManagementOperation { create, delete, attribute, geometry }

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