Edit feature attachments

View on GitHub

Add, delete, and download attachments for features from a service.

Image of edit feature attachments

Use case

Attachments provide a flexible way to manage additional information that is related to your features. Attachments allow you to add files to individual features, including: PDFs, text documents, or any other type of file. For example, if you have a feature representing a building, you could use attachments to add multiple photographs of the building taken from several angles, along with PDF files containing the building's deed and tax information.

How to use the sample

Tap a feature on the map to open a bottom sheet displaying the number of attachments. Tap on the view icon button to view the attachments. Tap the delete button to remove the attachments. Tap the Add Attachment button to add attachments to the feature.

How it works

  1. Create a ServiceFeatureTable from a URL.
  2. Create a FeatureLayer object from the service feature table.
  3. Select features from the feature layer with selectFeatures().
  4. To fetch the feature's attachments, cast to an ArcGISFeature and use ArcGISFeature.fetchAttachments().
  5. To add an attachment to the selected ArcGISFeature, create an attachment and use ArcGISFeature.addAttachment().
  6. To delete an attachment from the selected ArcGISFeature, use ArcGISFeature.deleteAttachment().
  7. After a change, apply the changes to the server using ServiceFeatureTable.applyEdits().

Relevant API

  • addAttachment
  • applyEdits
  • ArcGISFeature
  • deleteAttachment
  • FeatureLayer
  • fetchAttachments
  • ServiceFeatureTable

Additional information

Attachments can only be added to and accessed on service feature tables when their hasAttachments property is true.

Tags

Edit and manage data, image, JPEG, PDF, picture, PNG, TXT

Sample Code

edit_feature_attachments.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
//
// 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 'dart:io';

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

import '../../utils/sample_state_support.dart';

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

  @override
  State<EditFeatureAttachments> createState() => _EditFeatureAttachmentsState();
}

class _EditFeatureAttachmentsState extends State<EditFeatureAttachments>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // Create a feature layer with a feature table.
  final _featureLayer = FeatureLayer.withFeatureTable(
    ServiceFeatureTable.withUri(
      Uri.parse(
        'https://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0',
      ),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ArcGISMapView(
        controllerProvider: () => _mapViewController,
        onMapViewReady: onMapViewReady,
        onTap: onTap,
      ),
    );
  }

  void onMapViewReady() {
    // Create a map with an ArcGISStreet basemap style.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISStreets);
    // Set the initial viewpoint for the map.
    map.initialViewpoint = Viewpoint.fromCenter(
      ArcGISPoint(
        x: -95.0,
        y: 40.0,
        spatialReference: SpatialReference.wgs84,
      ),
      scale: 1e8,
    );

    // Add the feature layer to the map.
    map.operationalLayers.add(_featureLayer);
    _mapViewController.arcGISMap = map;
  }

  void onTap(Offset localPosition) async {
    // Clear the selection on the feature layer.
    _featureLayer.clearSelection();

    // Do an identify on the feature layer and select a feature.
    final identifyLayerResult = await _mapViewController.identifyLayer(
      _featureLayer,
      screenPoint: localPosition,
      tolerance: 5.0,
      maximumResults: 1,
    );

    // If there are features identified, show the bottom sheet to display the
    // attachment information for the selected feature.
    final features =
        identifyLayerResult.geoElements.whereType<Feature>().toList();
    if (features.isNotEmpty) {
      _featureLayer.selectFeatures(features);
      final selectedFeature = features.first as ArcGISFeature;
      if (mounted) _showBottomSheet(selectedFeature);
    }
  }

  // Show the bottom sheet to display the attachment information.
  void _showBottomSheet(ArcGISFeature selectedFeature) {
    showModalBottomSheet(
      context: context,
      builder: (context) => AttachmentsOptions(
        arcGISFeature: selectedFeature,
        applyEdits: _applyEdits,
      ),
    );
  }

  // Apply the changes to the feature table.
  Future<void> _applyEdits(ArcGISFeature selectedFeature) async {
    final serviceFeatureTable =
        _featureLayer.featureTable! as ServiceFeatureTable;
    try {
      // Update the selected feature locally.
      await serviceFeatureTable.updateFeature(selectedFeature);
      // Apply the edits to the service.
      await serviceFeatureTable.applyEdits();
    } catch (e) {
      if (mounted) _showErrorDialog(context, e);
    }
    return Future.value();
  }
}

//
// A widget to display the attachment information for the selected feature.
//
class AttachmentsOptions extends StatefulWidget {
  final ArcGISFeature arcGISFeature;
  final Function(ArcGISFeature) applyEdits;

  const AttachmentsOptions({
    super.key,
    required this.arcGISFeature,
    required this.applyEdits,
  });

  @override
  State<AttachmentsOptions> createState() => _AttachmentsOptionsState();
}

// State class for the AttachmentsOptions.
class _AttachmentsOptionsState extends State<AttachmentsOptions>
    with SampleStateSupport {
  late final String damageType;
  var attachments = <Attachment>[];
  var isLoading = false;

  @override
  void initState() {
    super.initState();
    damageType = widget.arcGISFeature.attributes['typdamage'];
    _loadAttachments();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            // Display the damage type and a close button.
            Container(
              color: Colors.purple,
              padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Damage Type: $damageType',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                 isLoading
                 ? const SizedBox(
                      height: 18,
                      width: 18,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                      ),
                    )
                  : const SizedBox.shrink(),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
            ),

            // Display the number of attachments.
            Padding(
              padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Number of Attachments: ${attachments.length}'),
                  ElevatedButton(
                    onPressed: addAttachment,
                    child: const Text('Add Attachment'),
                  ),
                ],
              ),
            ),
            const Divider(
              color: Colors.purple,
            ),

            // Display each attachment with view and delete buttons.
            SingleChildScrollView(
              child: Column(
                children: [
                  ListView.builder(
                    itemCount: attachments.length,
                    shrinkWrap: true,
                    padding: const EdgeInsets.all(2),
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(attachments[index].name),
                        subtitle: Text(attachments[index].contentType),
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            IconButton(
                              icon: const Icon(Icons.remove_red_eye),
                              onPressed: () =>
                                  viewAttachment(attachments[index]),
                            ),
                            IconButton(
                              icon: const Icon(Icons.delete),
                              onPressed: () =>
                                  deleteAttachment(attachments[index]),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  // Delete an attachment from the selected feature.
  void deleteAttachment(Attachment attachment) async {
    setState(() => isLoading = true);
    await widget.arcGISFeature.deleteAttachment(attachment);
    await widget.applyEdits(widget.arcGISFeature);

    _loadAttachments();
    setState(() => isLoading = false);
  }

  // View an attachment from the selected feature in a dialog.
  void viewAttachment(Attachment attachment) async {
    setState(() => isLoading = true);

    final data = await attachment.fetchData();
    setState(() => isLoading = false);

    // Display the attachment image/pdf file in a dialog.
    if (mounted) {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(attachment.name),
            content: SizedBox(
              height: 300,
              child: Image.memory(data),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.save),
                onPressed: () {
                  // Save the attachment to the device.
                  FilePicker.platform.saveFile(
                    dialogTitle: 'Save Attachment',
                    fileName: attachment.name,
                    bytes: data,
                    lockParentWindow: true,
                  );
                },
              ),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }

  // Add an attachment to the selected feature by FilePicker.
  void addAttachment() async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: false,
      type: FileType.custom,
      allowedExtensions: ['png', 'jpg', 'jpeg', 'pdf', 'txt'],
    );

    if (result != null) {
      setState(() => isLoading = true);

      final platformFile = result.files.single;
      final file = File(platformFile.path!);

      // Get the context type for the file.
      final fileExtension = platformFile.extension?.toLowerCase();
      final contentType = getContextType(fileExtension ?? 'default');
      final fileBytes = await file.readAsBytes();

      await widget.arcGISFeature.addAttachment(
        name: platformFile.name,
        contentType: contentType,
        data: fileBytes,
      );
      await widget.applyEdits(widget.arcGISFeature);
      _loadAttachments();

      setState(() => isLoading = false);
    }
  }

  // Load and update the attachments for the selected feature.
  Future<void> _loadAttachments() async {
    try {
      var fetchedAttachments = await widget.arcGISFeature.fetchAttachments();
      setState(() {
        attachments = fetchedAttachments;
        isLoading = false;
      });
    } catch (e) {
      if (mounted) _showErrorDialog(context, e);
      setState(() => isLoading = false);
    }
  }

  String getContextType(String fileExtension) {
    switch (fileExtension) {
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'pdf':
        return 'application/pdf';
      case 'txt':
        return 'text/plain';
      default:
        return 'application/octet-stream';
    }
  }
}

// Show an error dialog.
void _showErrorDialog(BuildContext context, dynamic error) {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: const Text('Error'),
      content: Text(error.toString()),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('OK'),
        ),
      ],
    ),
  );
}

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