Edit with branch versioning

View on GitHub

Create, query and edit a specific server version using service geodatabase.

Image of edit with branch versioning

Use case

Workflows often progress in discrete stages, with each stage requiring the allocation of a different set of resources and business rules. Typically, each stage in the overall process represents a single unit of work, such as a work order or job. To manage these, you can create a separate, isolated version and modify it. Once this work is complete, you can integrate the changes into the default version.

How to use the sample

Once loaded, the map will zoom to the extent of the feature layer. The current version is indicated at the top of the map. Tap on "Create" to open a bottom modal sheet to specify the version information (name, access, and description). See the Additional information section for restrictions on the version name.

Tap "Create" to create the version with the information that you specified. Select a feature to edit an attribute and/or tap a second time anywhere on the map to relocate the point.

Tap the Switch button in the bottom right corner to switch back and forth between the version you created and the default version. Edits will automatically be applied to your version when switching to the default version.

How it works

  1. Create and load a ServiceGeodatabase with a feature service URL that has enabled Version Management.
  2. Get the ServiceFeatureTable from the service geodatabase.
  3. Create a FeatureLayer from the service feature table.
  4. Create ServiceVersionParameters with a unique name, VersionAccess, and description.
    • Note - See the additional information section for more restrictions on the version name.
  5. Create a new version calling ServiceGeodatabase.createVersion passing in the service version parameters.
  6. Await ServiceGeodatabase.createVersion signal to obtain the ServiceVersionInfo of the version created.
  7. Switch to the version you have just created using ServiceGeodatabase.switchVersion, passing in the version name obtained from the service version info from step 6.
  8. Select a Feature from the map to edit its "TYPDAMAGE" attribute and location.
  9. Apply these edits to your version by calling ServiceGeodatabase.applyEdits().
  10. Switch back and forth between your version and the default version to see how the two versions differ.

Relevant API

  • FeatureLayer
  • ServiceFeatureTable
  • ServiceGeodatabase
  • ServiceGeodatabase.applyEdits
  • ServiceGeodatabase.createVersion
  • ServiceGeodatabase.switchVersion
  • ServiceGeodatabase.undoLocalEdits
  • ServiceVersionInfo
  • ServiceVersionParameters
  • VersionAccess

About the data

The feature layer used in this sample is Damage to commercial buildings located in Naperville, Illinois.

Additional information

Credentials:

  • Username: editor01
  • Passowrd: S7#i2LWmYH75

The name of the version must meet the following criteria:

  1. Must not exceed 62 characters
  2. Must not include: Period (.), Semicolon (;), Single quotation mark ('), Double quotation mark (")
  3. Must not include a space for the first character
  • Note - the version name will have the username and a period (.) prepended to it. E.g "editor01.MyNewUniqueVersionName"

Branch versioning access permission:

  1. VersionAccess.Public - Any portal user can view and edit the version.
  2. VersionAccess.Protected - Any portal user can view, but only the version owner, feature layer owner, and portal administrator can edit the version.
  3. VersionAccess.Private - Only the version owner, feature layer owner, and portal administrator can view and edit the version.

Tags

branch versioning, edit, version control, version management server

Sample Code

edit_with_branch_versioning.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
// 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:flutter/material.dart';

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

  @override
  State<EditWithBranchVersioning> createState() =>
      _EditWithBranchVersioningState();
}

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

  // Create an instance of the model class for this sample.
  final _model = EditWithBranchVersioningModel();

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

  // A boolean value indicating whether bottom feature sheet is available.
  bool _featureBottomSheetVisible = false;

  @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,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // A button to open a bottom sheet for creating a new branch version.
                    ElevatedButton(
                      onPressed: () async {
                        await showCreateVersionModalBottomSheet(
                          context,
                          _model,
                        );
                      },
                      child: const Text('Create'),
                    ),
                    // A button to select a version to switch to.
                    ElevatedButton(
                      onPressed:
                          _model.isVersionCreated
                              ? () => showSwitchVersionDialog(context, _model)
                              : null,
                      child: const Text('Switch'),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            LoadingIndicator(visible: !_ready),
            // Display a banner with the current version at the top.
            SafeArea(
              child: IgnorePointer(
                child: Container(
                  padding: const EdgeInsets.all(10),
                  color: Colors.white.withValues(alpha: 0.7),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ValueListenableBuilder(
                        valueListenable: _model.currentVersionNameNotifier,
                        builder: (context, currentVersionName, child) {
                          return Text(
                            'Version: $currentVersionName',
                            textAlign: TextAlign.center,
                            style: Theme.of(context).textTheme.labelMedium,
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      // The Feature Details bottom sheet.
      bottomSheet:
          _featureBottomSheetVisible
              ? buildFeatureDetails(context, _model.selectedFeature!)
              : null,
    );
  }

  Future<void> onMapViewReady() async {
    // Call the setUp method in the model class to configure the service geodatabase and feature layer.
    await _model.setUp();

    // Set the configured map to the map view controller.
    _mapViewController.arcGISMap = _model.map;

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

  Future<void> onTap(Offset localPosition) async {
    if (_model.selectedFeature != null && !_model.onDefaultVersion) {
      final mapPoint = _mapViewController.screenToLocation(
        screen: localPosition,
      );

      // Show the move confirmation dialog if a feature is already selected.
      _showMoveConfirmationDialog(_model.selectedFeature!, mapPoint!);
      return;
    } else {
      // Clear the selection of the feature layer.
      _model.clearSelection();
    }

    // Do an identify on the feature layer and select a feature.
    final identifyLayerResult = await _mapViewController.identifyLayer(
      _model.featureLayer,
      screenPoint: localPosition,
      tolerance: 5,
    );

    // If there are features identified select the first feature.
    final features =
        identifyLayerResult.geoElements.whereType<Feature>().toList();

    if (features.isNotEmpty) {
      _model.selectFeature(features.first);

      // Show the bottom modal sheet with the feature's attributes.
      if (mounted) {
        setState(() {
          _featureBottomSheetVisible = true;
        });
      }
    }
  }

  Widget buildFeatureDetails(BuildContext context, Feature feature) {
    // Get the required feature attributes.
    final placeName = feature.attributes['placename'] as String?;
    final damageType = feature.attributes['typdamage'] as String?;

    return Container(
      padding: EdgeInsets.fromLTRB(
        20,
        20,
        20,
        max(
          20,
          View.of(context).viewPadding.bottom /
              View.of(context).devicePixelRatio,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text(
                placeName ?? 'Feature Details',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const Spacer(),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed:
                    () => setState(() {
                      _featureBottomSheetVisible = false;
                      _model.clearSelection();
                    }),
              ),
            ],
          ),
          const Divider(),
          Text('Damage Type: ${damageType ?? 'Unknown'}'),
          const Divider(),
          TextButton(
            onPressed:
                _model.onDefaultVersion
                    ? null
                    : () {
                      setState(() {
                        _editDamageType(feature);
                      });
                    },
            child: const Text('Edit Damage Type'),
          ),
        ],
      ),
    );
  }

  void _showMoveConfirmationDialog(Feature feature, ArcGISPoint mapPoint) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('Confirm Move'),
            content: const Text('Do you want to move the selected feature?'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  _model.clearSelection();
                  setState(() => _featureBottomSheetVisible = false);
                },
                child: const Text('Cancel'),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  setState(() {
                    feature.geometry = mapPoint;
                    _model.updateFeature();
                    setState(() => _featureBottomSheetVisible = false);
                  });
                },
                child: const Text('Move'),
              ),
            ],
          ),
    );
  }

  void _editDamageType(Feature feature) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Damage Type'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children:
                DamageType.values.map((damageType) {
                  return ListTile(
                    title: Text(damageType.label),
                    onTap: () {
                      Navigator.of(context).pop();

                      // Update the feature's attribute with the selected value.
                      feature.attributes['typdamage'] = damageType.label;
                      _model.updateFeature();

                      setState(() {
                        _featureBottomSheetVisible = false;
                      });
                    },
                  );
                }).toList(),
          ),
        );
      },
    );
  }

  Future<void> showCreateVersionModalBottomSheet(
    BuildContext context,
    EditWithBranchVersioningModel model,
  ) async {
    final nameController = TextEditingController();
    final descriptionController = TextEditingController();
    var selectedAccess = VersionAccess.public;

    return showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Padding(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        children: [
                          TextField(
                            controller: nameController,
                            decoration: const InputDecoration(
                              labelText: 'Name',
                            ),
                          ),
                          TextField(
                            controller: descriptionController,
                            decoration: const InputDecoration(
                              labelText: 'Description',
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8),
                            child: DropdownMenu(
                              initialSelection: selectedAccess,
                              onSelected: (newValue) {
                                if (newValue != null) {
                                  setModalState(() {
                                    // Update the selected access value when a new value is selected from the dropdown menu.
                                    selectedAccess = newValue;
                                  });
                                }
                              },
                              // Display the version access values in a dropdown.
                              dropdownMenuEntries:
                                  VersionAccess.values.map((value) {
                                    return DropdownMenuEntry(
                                      value: value,
                                      label: value.name,
                                    );
                                  }).toList(),
                            ),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              ElevatedButton(
                                onPressed: () => Navigator.of(context).pop(),
                                child: const Text('Cancel'),
                              ),
                              ElevatedButton(
                                onPressed: () async {
                                  // Create a new version by defining service version parameters from the user input.
                                  if (nameController.text.isNotEmpty) {
                                    final parameters =
                                        ServiceVersionParameters()
                                          ..name = nameController.text
                                          ..description =
                                              descriptionController.text
                                          ..access = selectedAccess;

                                    try {
                                      await model.createVersion(parameters);
                                      setState(() {
                                        model.isVersionCreated = true;
                                      });
                                      if (context.mounted) {
                                        Navigator.of(context).pop();
                                      }
                                    } on ArcGISException catch (e) {
                                      if (context.mounted) {
                                        Navigator.of(context).pop();
                                        // Show an error message if an exception occurs.
                                        await showDialog<void>(
                                          context: context,
                                          builder: (context) {
                                            var errorMessageStrings = e
                                                .additionalMessage
                                                .split(RegExp(r'\s+'));

                                            if (errorMessageStrings.contains(
                                              'Extended',
                                            )) {
                                              errorMessageStrings =
                                                  errorMessageStrings.sublist(
                                                    0,
                                                    errorMessageStrings.length -
                                                        4,
                                                  );
                                            }
                                            final cleanedMessage =
                                                errorMessageStrings.join(' ');
                                            return AlertDialog(
                                              title: const Text('Error'),
                                              content: Text(
                                                'Error: $cleanedMessage',
                                              ),
                                              actions: [
                                                TextButton(
                                                  onPressed:
                                                      () =>
                                                          Navigator.of(
                                                            context,
                                                          ).pop(),
                                                  child: const Text('OK'),
                                                ),
                                              ],
                                            );
                                          },
                                        );
                                      }
                                    }
                                  } else {
                                    // Show an error message if the fields are empty.
                                    await showDialog<void>(
                                      context: context,
                                      builder: (context) {
                                        return AlertDialog(
                                          title: const Text('Error'),
                                          content: const Text(
                                            'Name cannot be empty',
                                          ),
                                          actions: [
                                            TextButton(
                                              onPressed:
                                                  () =>
                                                      Navigator.of(
                                                        context,
                                                      ).pop(),
                                              child: const Text('OK'),
                                            ),
                                          ],
                                        );
                                      },
                                    );
                                  }
                                },
                                child: const Text('Create'),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  Future<void> showSwitchVersionDialog(
    BuildContext context,
    EditWithBranchVersioningModel model,
  ) async {
    return showDialog<void>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Switch Version'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children:
                model.existingVersionNames.map((versionName) {
                  return ListTile(
                    title: Text(versionName),
                    onTap: () async {
                      Navigator.of(context).pop();
                      try {
                        await model.switchToVersion(versionName);
                        // catch ArcGISException when switching to a version fails.
                        // ignore: avoid_catches_without_on_clauses
                      } catch (e) {
                        // Show an error message if an exception occurs.
                        if (context.mounted) {
                          await showDialog<void>(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: const Text('Error'),
                                content: Text('Error: $e'),
                                actions: [
                                  TextButton(
                                    onPressed:
                                        () => Navigator.of(context).pop(),
                                    child: const Text('OK'),
                                  ),
                                ],
                              );
                            },
                          );
                        }
                      }
                    },
                  );
                }).toList(),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Cancel'),
            ),
          ],
        );
      },
    );
  }
}

// A model class to manage the service data, branch versions, and features that are used in this sample.
class EditWithBranchVersioningModel extends ChangeNotifier {
  EditWithBranchVersioningModel() {
    // Initialize the current version name with the default version name from the service geodatabase.
    currentVersionNameNotifier.value = serviceGeodatabase.defaultVersionName;
  }

  // The names of the versions added by the user.
  //
  // - Note: To get a full list of existing versions in the service geodatabase, use `ServiceGeodatabase.versions`.
  // In this sample, only the default version and versions created in current session are shown.
  final existingVersionNames = <String>[];

  // Initially center the map's viewpoint on Naperville, IL, USA.
  final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreets)
    ..initialViewpoint = Viewpoint.fromCenter(
      ArcGISPoint(
        x: -9811970,
        y: 5127180,
        spatialReference: SpatialReference.webMercator,
      ),
      scale: 4000,
    );

  // Create a service geodatabase from a feature service URL.
  final serviceGeodatabase = ServiceGeodatabase.withUri(
    Uri.parse(
      'https://sampleserver7.arcgisonline.com/server/rest/services/DamageAssessment/FeatureServer',
    ),
  );

  // Use a ValueNotifier to track the current version name.
  final currentVersionNameNotifier = ValueNotifier<String>('');

  // Update the current version name and notify listeners.
  void updateCurrentVersionName() {
    currentVersionNameNotifier.value = serviceGeodatabase.versionName;
  }

  late FeatureLayer featureLayer;
  Feature? selectedFeature;

  // A boolean value indicating whether the geodatabase's current version is its default version.
  bool get onDefaultVersion =>
      serviceGeodatabase.versionName == serviceGeodatabase.defaultVersionName;

  // A boolean value indicating whether a version has been created.
  bool isVersionCreated = false;

  // Sets up the service geodatabase and feature layer.
  Future<void> setUp() async {
    // Adds the credential to access the feature service for the service geodatabase.
    final credential = await getPublicSampleCredential();
    ArcGISEnvironment.authenticationManager.arcGISCredentialStore.add(
      credential: credential,
    );
    await serviceGeodatabase.load();
    existingVersionNames.add(serviceGeodatabase.defaultVersionName);

    // Update the current version name after loading the service geodatabase.
    updateCurrentVersionName();

    // Creates a feature layer from the geodatabase and adds it to the map.
    final serviceFeatureTable = serviceGeodatabase.getTable(layerId: 0)!;
    featureLayer = FeatureLayer.withFeatureTable(serviceFeatureTable);
    map.operationalLayers.add(featureLayer);
  }

  // Creates a new version in the service using given parameters.
  // - ServiceVersionParameters parameters: The properties of the new version.
  // - Returns: The name of the created version.
  Future<String> createVersion(ServiceVersionParameters parameters) async {
    final versionInfo = await serviceGeodatabase.createVersion(
      newVersion: parameters,
    );
    existingVersionNames.add(versionInfo.name);
    // Set the flag to true when a version is created.
    isVersionCreated = true;
    // Switch to the newly created version.
    await switchToVersion(versionInfo.name);

    return versionInfo.name;
  }

  // Switches the geodatabase version to a version with a given name.
  // - Parameter versionName: The name of the version to connect to.
  Future<void> switchToVersion(String versionName) async {
    if (onDefaultVersion) {
      // Discards the local edits when on the default branch.
      // Making edits on default branch is disabled, but this is left here for parity.
      await serviceGeodatabase.undoLocalEdits();
    } else {
      // Applies the local edits when on a user created branch.
      await serviceGeodatabase.applyEdits();
    }
    clearSelection();
    await serviceGeodatabase.switchVersion(versionName: versionName);
    // Update the current version name.
    updateCurrentVersionName();
  }

  // Selects a feature on the feature layer.
  void selectFeature(Feature feature) {
    featureLayer.selectFeature(feature);
    selectedFeature = feature;
  }

  // Clears the selected feature.
  void clearSelection() {
    featureLayer.clearSelection();
    selectedFeature = null;
  }

  // Updates the selected feature in it's feature table.
  Future<void> updateFeature() async {
    if (selectedFeature?.featureTable == null) return;
    await selectedFeature!.featureTable!.updateFeature(selectedFeature!);
    clearSelection();
  }

  Future<ArcGISCredential> getPublicSampleCredential() async {
    // The public credentials for the data in this sample.
    // Note: Never hardcode login information in a production application. This is done solely for the sake of the sample.
    final credential = await TokenCredential.create(
      uri: Uri.parse(
        'https://sampleserver7.arcgisonline.com/server/rest/services/DamageAssessment/FeatureServer',
      ),
      username: 'editor01',
      password: 'S7#i2LWmYH75',
    );
    return credential;
  }
}

// The damage type of a feature.
enum DamageType {
  destroyed,
  major,
  minor,
  affected,
  inaccessible,
  defaultType;

  String get label {
    switch (this) {
      case DamageType.destroyed:
        return 'Destroyed';
      case DamageType.major:
        return 'Major';
      case DamageType.minor:
        return 'Minor';
      case DamageType.affected:
        return 'Affected';
      case DamageType.inaccessible:
        return 'Inaccessible';
      case DamageType.defaultType:
        return 'Default';
    }
  }
}

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