Skip to content
View on GitHub

Find dynamic entities from a data source that match a query.

Image of query dynamic entities

Use case

Developers can query a DynamicEntityDataSource to find dynamic entities that meet spatial and/or attribute criteria. The query returns a collection of dynamic entities matching the DynamicEntityQueryParameters or track IDs at the moment the query is executed.

An example of this is a flight tracking app that monitors airspace near a particular airport, allowing the user to monitor flights based on different criteria such as arrival airport or flight number.

How to use the sample

Tap the "Query Flights" button and select a query to perform from the menu. Once the query is complete, a list of the resulting flights will be displayed. Tap on a flight to see its latest attributes in real-time.

How it works

  1. Create a DynamicEntityDataSource to stream dynamic entity events.
  2. Create DynamicEntityQueryParameters and set its properties:
    • To spatially filter results, set geometry and spatialRelationship.
    • To query entities with certain attribute values, set whereClause.
    • To get entities with specific track IDs, modify the trackIDs collection.
  3. To perform a dynamic entities query, call DynamicEntityDataSource.queryDynamicEntities to query with spatial and/or attribute filters, or call DynamicEntityDataSource.queryDynamicEntitiesByTrackIds if you want to query only by track IDs.
  4. When complete, get the dynamic entities from the result using DynamicEntityQueryResult.iterator().
  5. Use DynamicEntity.onDynamicEntityChanged to receive change notifications.
  6. Get the new observation from DynamicEntityChangedInfo.receivedObservation and use dynamicEntityPurged to determine whether a dynamic entity has been purged.

Relevant API

  • DynamicEntity
  • DynamicEntityChangedInfo
  • DynamicEntityDataSource
  • DynamicEntityLayer
  • DynamicEntityObservation
  • DynamicEntityQueryParameters
  • DynamicEntityQueryResult

About the data

This sample uses the PHX Air Traffic JSON portal item, which is hosted on ArcGIS Online and downloaded automatically. The file contains JSON data for mock air traffic around the Phoenix Sky Harbor International Airport in Phoenix, AZ, USA. The decoded data is used to simulate dynamic entity events through a CustomDynamicEntityDataSource, which is displayed on the map with a DynamicEntityLayer.

Additional information

A dynamic entities query is performed on the most recent observation of each dynamic entity in the data source at the time the query is executed. As entities change, they may no longer match the original query parameters.

Tags

data, dynamic, entity, live, query, real-time, search, stream, track

Sample Code

query_dynamic_entities.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
//
// Copyright 2026 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import 'dart:async';
import 'dart:convert';
import 'dart:io';

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

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

  @override
  State<QueryDynamicEntities> createState() => _QueryDynamicEntitiesState();
}

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

  // Graphics overlay for displaying the PHX airport buffer graphic.
  final _bufferGraphicsOverlay = GraphicsOverlay();

  // The dynamic entity layer displayed on the map.
  late final DynamicEntityLayer _dynamicEntityLayer;

  // The custom data source streaming mock air traffic observations.
  CustomDynamicEntityDataSource? _dataSource;

  // A geometry representing a 15 mile buffer around Phoenix Sky Harbor (PHX).
  late final Polygon _phoenixAirportBuffer;

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

  // State for the non-modal query results sheet.
  var _isResultsSheetVisible = false;
  QuerySelection? _currentSelection;
  List<DynamicEntity> _currentEntities = const [];

  @override
  void dispose() {
    unawaited(_dataSource?.disconnect());
    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,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // Button to toggle overview or full model sublayers.
                    ElevatedButton(
                      onPressed: _showQueryMenu,
                      child: const Text('Query Flights'),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            LoadingIndicator(visible: !_ready),
          ],
        ),
      ),
      bottomSheet: _isResultsSheetVisible
          ? _QueryResultsSheet(
              selection: _currentSelection!,
              entities: _currentEntities,
              onClose: _closeResultsSheet,
            )
          : null,
    );
  }

  Future<void> onMapViewReady() async {
    // Create a map with a topographic basemap and an initial viewpoint.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISTopographic)
      ..initialViewpoint = Viewpoint.withLatLongScale(
        latitude: 33.4352,
        longitude: -112.0101,
        scale: 1266500,
      );

    // Create a 15-mile geodetic buffer around Phoenix airport.
    final phxPoint = ArcGISPoint(
      x: -112.0101,
      y: 33.4352,
      spatialReference: SpatialReference.wgs84,
    );
    _phoenixAirportBuffer = GeometryEngine.bufferGeodetic(
      geometry: phxPoint,
      distance: 15,
      distanceUnit: LinearUnit(unitId: LinearUnitId.miles),
      maxDeviation: double.nan,
      curveType: GeodeticCurveType.geodesic,
    );

    // Configure a graphics overlay to display the buffer polygon.
    _configureBufferOverlay();
    _mapViewController.graphicsOverlays.add(_bufferGraphicsOverlay);

    // Load and configure the dynamic entity layer.
    _loadDynamicEntityLayer();
    _configureDynamicEntityLayer(_dynamicEntityLayer);
    map.operationalLayers.add(_dynamicEntityLayer);

    // Set the map to the map view.
    _mapViewController.arcGISMap = map;

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

  // Configure the graphics overlay to display the PHX airport buffer.
  void _configureBufferOverlay() {
    final blackLineSymbol = SimpleLineSymbol(color: Colors.black);
    final fillSymbol = SimpleFillSymbol(
      color: Colors.red.withValues(alpha: 0.1),
      outline: blackLineSymbol,
    );
    final bufferGraphic = Graphic(
      geometry: _phoenixAirportBuffer,
      symbol: fillSymbol,
    );

    _bufferGraphicsOverlay.graphics.clear();
    _bufferGraphicsOverlay.graphics.add(bufferGraphic);
    _bufferGraphicsOverlay.isVisible = false;
  }

  // Load the dynamic entity layer with a custom data source.
  void _loadDynamicEntityLayer() {
    final listPaths = GoRouter.of(context).state.extra! as List<String>;

    // Create a custom data source that streams PHX air traffic observations.
    final provider = _PhxAirTrafficProvider(localJsonPath: listPaths.first);
    _dataSource = CustomDynamicEntityDataSource(provider);

    // Create a dynamic entity later from the custom data source.
    _dynamicEntityLayer = DynamicEntityLayer(_dataSource!);
  }

  // Configure the dynamic entity layer to show track lines and labels.
  void _configureDynamicEntityLayer(DynamicEntityLayer layer) {
    layer.trackDisplayProperties
      ..showPreviousObservations = true
      ..showTrackLine = true
      ..maximumObservations = 20;

    // Keep default renderers; only configure labels.
    final labelDefinition = LabelDefinition(
      labelExpression: SimpleLabelExpression(
        simpleExpression: '[flight_number]',
      ),
      textSymbol: TextSymbol(color: Colors.red, size: 12),
    )..placement = LabelingPlacement.pointAboveCenter;

    layer.labelDefinitions.add(labelDefinition);
    layer.labelsEnabled = true;
  }

  // Show a menu for selecting the type of query to perform.
  Future<void> _showQueryMenu() async {
    final selected = await showModalBottomSheet<QuerySelection>(
      context: context,
      builder: (context) => SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.my_location),
              title: const Text('Within 15 Miles of PHX'),
              onTap: () => Navigator.pop(context, (
                type: QueryType.geometry,
                trackId: null,
              )),
            ),
            ListTile(
              leading: const Icon(Icons.flight_land),
              title: const Text('Arriving in PHX'),
              onTap: () => Navigator.pop(context, (
                type: QueryType.attributes,
                trackId: null,
              )),
            ),
            ListTile(
              leading: const Icon(Icons.tag),
              title: const Text('With Flight Number'),
              onTap: () async {
                final navigator = Navigator.of(context);
                final flightNumber = await _promptForFlightNumber();
                if (flightNumber == null || flightNumber.trim().isEmpty) {
                  return;
                }
                navigator.pop((
                  type: QueryType.trackId,
                  trackId: flightNumber.trim(),
                ));
              },
            ),
          ],
        ),
      ),
    );

    // If a selection was made, run the corresponding query.
    if (selected == null) return;
    await _runQuery(selected);
  }

  // Prompt the user to enter a flight number for the track ID query.
  Future<String?> _promptForFlightNumber() async {
    final controller = TextEditingController();
    return showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Enter a Flight Number to Query'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(labelText: 'Flight Number'),
            autofocus: true,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('Cancel'),
            ),
            FilledButton(
              onPressed: () => Navigator.pop(context, controller.text),
              child: const Text('Done'),
            ),
          ],
        );
      },
    );
  }

  // Run the selected query and display the results in a bottom sheet.
  Future<void> _runQuery(QuerySelection selection) async {
    final dataSource = _dataSource;
    if (dataSource == null) return;
    // Show the buffer graphic only for geometry queries.
    _bufferGraphicsOverlay.isVisible = selection.type == QueryType.geometry;

    // The result of the dynamic entity query.
    DynamicEntityQueryResult queryResult;

    // Execute the appropriate query based on the selection.
    switch (selection.type) {
      case QueryType.geometry:
        final params = DynamicEntityQueryParameters()
          ..geometry = _phoenixAirportBuffer
          ..spatialRelationship = SpatialRelationship.intersects;
        queryResult = await dataSource.queryDynamicEntities(params);
      case QueryType.attributes:
        final params = DynamicEntityQueryParameters()
          ..whereClause = "status = 'In flight' AND arrival_airport = 'PHX'";
        queryResult = await dataSource.queryDynamicEntities(params);
      case QueryType.trackId:
        queryResult = await dataSource.queryDynamicEntitiesByTrackIds([
          selection.trackId!,
        ]);
    }

    // Collect the query results into a list.
    final entities = queryResult.dynamicEntities().toList(growable: false);
    _dynamicEntityLayer.clearSelection();
    if (entities.isNotEmpty) {
      _dynamicEntityLayer.selectDynamicEntities(entities);
    }

    // Show the query results in a bottom sheet.
    _showQueryResultsSheet(selection, entities: entities);
  }

  void _showQueryResultsSheet(
    QuerySelection selection, {
    required List<DynamicEntity> entities,
  }) {
    setState(() {
      _currentSelection = selection;
      _currentEntities = entities;
      _isResultsSheetVisible = true;
    });
  }

  void _closeResultsSheet() {
    setState(() {
      _isResultsSheetVisible = false;
      _currentSelection = null;
      _currentEntities = const [];
    });

    // Clear selection and hide buffer when the results sheet is closed.
    _dynamicEntityLayer.clearSelection();
    _bufferGraphicsOverlay.isVisible = false;
  }
}

// Enum representing the types of queries available.
enum QueryType { geometry, attributes, trackId }

typedef QuerySelection = ({QueryType type, String? trackId});

// Create a result label based on the query selection.
String _resultLabel(QuerySelection selection) {
  return switch (selection.type) {
    QueryType.geometry => 'Flights within 15 miles of PHX',
    QueryType.attributes => 'Flights arriving in PHX',
    QueryType.trackId => 'Flights matching number: ${selection.trackId ?? ''}',
  };
}

class _DynamicEntityObservationTile extends StatefulWidget {
  const _DynamicEntityObservationTile({required this.entity});

  // The dynamic entity to observe.
  final DynamicEntity entity;

  @override
  State<_DynamicEntityObservationTile> createState() =>
      _DynamicEntityObservationTileState();
}

class _DynamicEntityObservationTileState
    extends State<_DynamicEntityObservationTile> {
  // Subscribe to the ArcGIS dynamic entity change stream.
  StreamSubscription<DynamicEntityChangedInfo>? _subscription;
  // Latest observation attributes pulled from the ArcGIS entity.
  Map<CaseInsensitiveString, dynamic> _attributes = const {};
  // Tracks whether the tile is expanded to show attributes.
  bool _isExpanded = false;

  @override
  void initState() {
    super.initState();
    // Seed the attributes with the latest observation, if any.
    // Uses the ArcGIS API to read the entity's most recent observation.
    _attributes = widget.entity.getLatestObservation()?.attributes ?? const {};

    // Listen for dynamic entity changes to keep the UI in sync.
    _subscription = widget.entity.onDynamicEntityChanged.listen((changedInfo) {
      if (changedInfo.dynamicEntityPurged) {
        // Clear attributes when the entity is purged from the stream.
        setState(() => _attributes = const {});
        return;
      }
      final attrs = changedInfo.receivedObservation?.attributes;
      if (attrs != null) {
        // Update attributes when a new observation arrives.
        setState(() => _attributes = attrs);
      }
    });
  }

  @override
  void dispose() {
    // Cancel the subscription to avoid memory leaks.
    _subscription?.cancel().ignore();
    _subscription = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // The flight number as the tile title when available.
    final flightNumber = _attributes['flight_number'] as String?;
    // Sort attributes to keep the list stable and readable.
    final sortedEntries = _attributes.entries.toList()
      ..sort((a, b) => a.key.compareTo(b.key));

    return ExpansionTile(
      title: Text(flightNumber ?? ''),
      initiallyExpanded: _isExpanded,
      onExpansionChanged: (expanded) => setState(() => _isExpanded = expanded),
      children: sortedEntries
          // Filter out null values and render the remaining attributes.
          .where((e) => e.value != null)
          .map(
            (e) => ListTile(
              dense: true,
              title: Text(_planeAttributeLabel(e.key)),
              trailing: Text(_formatAttributeValue(e.value)),
            ),
          )
          .toList(),
    );
  }

  // Map attribute keys to labels.
  static String _planeAttributeLabel(String key) {
    switch (key) {
      case 'aircraft':
        return 'Aircraft';
      case 'altitude_feet':
        return 'Altitude (ft)';
      case 'arrival_airport':
        return 'Arrival Airport';
      case 'flight_number':
        return 'Flight Number';
      case 'heading':
        return 'Heading';
      case 'speed':
        return 'Speed';
      case 'status':
        return 'Status';
      default:
        return key;
    }
  }

  // Format attribute values for display.
  static String _formatAttributeValue(Object? value) {
    if (value == null) return '';
    if (value is String) return value;
    if (value is num) return value.toStringAsFixed(2);
    return value.toString();
  }
}

class _QueryResultsSheet extends StatelessWidget {
  const _QueryResultsSheet({
    required this.selection,
    required this.entities,
    required this.onClose,
  });

  // The query selection that produced the results.
  final QuerySelection selection;
  // The list of dynamic entities returned by the query.
  final List<DynamicEntity> entities;
  // Callback to close the results sheet.
  final VoidCallback onClose;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: DraggableScrollableSheet(
        expand: false,
        initialChildSize: 0.4,
        builder: (context, scrollController) {
          return Material(
            clipBehavior: Clip.antiAlias,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            child: Column(
              children: [
                ListTile(
                  title: const Text('Query Results'),
                  subtitle: Text(_resultLabel(selection)),
                  trailing: IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: onClose,
                  ),
                ),
                const Divider(height: 1),
                Expanded(
                  child: Builder(
                    builder: (context) {
                      // Empty state when no entities matched the query.
                      if (entities.isEmpty) {
                        return const Center(
                          child: Padding(
                            padding: EdgeInsets.all(16),
                            child: Text(
                              'There are no flights to display for this query.',
                              textAlign: TextAlign.center,
                            ),
                          ),
                        );
                      }

                      // A scrollable list of dynamic entity observations.
                      return ListView.builder(
                        controller: scrollController,
                        itemCount: entities.length,
                        itemBuilder: (context, index) {
                          return _DynamicEntityObservationTile(
                            entity: entities[index],
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

// Enum representing the keys for plane attributes.
enum _PlaneAttributeKey {
  aircraft,
  altitudeFeet,
  arrivalAirport,
  flightNumber,
  heading,
  speed,
  status;

  // Provide the field name associated with the attribute key.
  String get fieldName {
    return switch (this) {
      _PlaneAttributeKey.aircraft => 'aircraft',
      _PlaneAttributeKey.altitudeFeet => 'altitude_feet',
      _PlaneAttributeKey.arrivalAirport => 'arrival_airport',
      _PlaneAttributeKey.flightNumber => 'flight_number',
      _PlaneAttributeKey.heading => 'heading',
      _PlaneAttributeKey.speed => 'speed',
      _PlaneAttributeKey.status => 'status',
    };
  }

  // Determine the field type based on the attribute key.
  FieldType get fieldType {
    return switch (this) {
      _PlaneAttributeKey.heading ||
      _PlaneAttributeKey.altitudeFeet ||
      _PlaneAttributeKey.speed => FieldType.float64,
      _ => FieldType.text,
    };
  }
}

// A custom dynamic entity data provider that streams mock air traffic data for PHX.
final class _PhxAirTrafficProvider extends CustomDynamicEntityDataProvider {
  // Constructor accepting the local JSON file path.
  _PhxAirTrafficProvider({required this.localJsonPath});

  // The local path to the JSON file containing mock air traffic observations.
  final String localJsonPath;

  // A flag indicating whether the provider is currently connected.
  bool _isConnected = false;

  @override
  Future<DynamicEntityDataSourceInfo> onLoad() async {
    // Define the fields for the dynamic entity data source.
    final fields = _PlaneAttributeKey.values
        .map(
          (k) => Field(
            type: k.fieldType,
            name: k.fieldName,
            alias: '',
            length: 0,
            isEditable: false,
            isNullable: true,
          ),
        )
        .toList(growable: false);

    // Define the data source info with fields and entity ID field.
    final info = DynamicEntityDataSourceInfo(
      entityIdFieldName: 'flight_number',
      fields: fields,
    )..spatialReference = SpatialReference.wgs84;

    return info;
  }

  @override
  Future<void> onConnect() async {
    if (_isConnected) return;
    _isConnected = true;

    // Start streaming mock air traffic observations.
    unawaited(_startStreaming());
  }

  @override
  Future<void> onDisconnect() async {
    if (!_isConnected) return;
    _isConnected = false;
  }

  // Start streaming mock air traffic observations from the local JSON file.
  Future<void> _startStreaming() async {
    final file = File(localJsonPath);

    // Decodes the plane from the line and uses it to create a new observation.
    final lines = file
        .openRead()
        .transform(utf8.decoder)
        .transform(const LineSplitter());

    // Stream each line as a new observation until disconnected.
    await for (final line in lines) {
      if (!_isConnected) return;

      final decoded = jsonDecode(line) as Map<String, dynamic>;
      final geometryJson = decoded['geometry'] as Map<String, dynamic>?;
      final attributesJson = decoded['attributes'] as Map<String, dynamic>?;

      final geometry = Geometry.fromJson(geometryJson!);
      handleEntityDataEvent(NewObservation(geometry, attributesJson!));

      // Delay the next observation to simulate live data.
      await Future<void>.delayed(const Duration(milliseconds: 100));
    }
  }
}

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