Query table statistics

View on GitHub

Query a table to get aggregated statistics back for a specific field.

Image of query table statistics

Use case

For example, a county boundaries table with population information can be queried to return aggregated results for the total, average, maximum, and minimum population, rather than downloading the values for every county and calculating the statistics manually.

How to use the sample

Pan and zoom to define the extent for the query. In the Settings panel, use the 'Only cities in current extent' checkbox to control whether the query includes only features in the visible extent, or use the 'Only cities greater than 5M' checkbox to filter the results to only those cities with a population greater than 5 million people. Tap the 'Get statistics' to perform the query. The query will return population-based statistics from the combined results of all features matching the query criteria.

How it works

  1. Create a ServiceFeatureTable with a URL to the feature service.
  2. Create StatisticsQueryParameters, and StatisticDefinition objects, and add to the parameters.
  3. Execute queryStatistics on the ServiceFeatureTable. Depending on the state of the two checkboxes, additional parameters are set.
  4. Display each StatisticRecord in the first returned QueryStatisticsResult.

Relevant API

  • QueryParameters
  • ServiceFeatureTable
  • StatisticDefinition
  • StatisticRecord
  • StatisticsQueryParameters
  • StatisticsQueryResult
  • StatisticType

Tags

analysis, average, bounding geometry, filter, intersect, maximum, mean, minimum, query, spatial query, standard deviation, statistics, sum, variance

Sample Code

query_table_statistics.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
//
// 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:math';

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

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

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

  @override
  State<QueryTableStatistics> createState() => _QueryTableStatisticsState();
}

class _QueryTableStatisticsState extends State<QueryTableStatistics>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // Create a ServiceFeatureTable from a URL.
  final _serviceFeatureTable = ServiceFeatureTable.withUri(
    Uri.parse(
      'https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0',
    ),
  );
  // A flag for when the map view is ready and controls can be used.
  var _ready = false;
  // A flag for whether to limit the query to cities within the current extent.
  var _onlyCitiesInCurrentExtent = true;
  // A flag for whether to limit the query to cities with population greater than 5 million.
  var _onlyCitiesGreaterThan5M = true;
  // A list of statistic definitions to apply to the query.
  final _statisticDefinitions = <StatisticDefinition>[];
  // A flag to display the query settings.
  var _settingsVisible = false;

  @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,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // A button to show the Settings bottom sheet.
                    ElevatedButton(
                      onPressed: () => setState(() => _settingsVisible = true),
                      child: const Text('Settings'),
                    ),
                    // A button to calculate the statistics.
                    ElevatedButton(
                      onPressed: queryStatistics,
                      child: const Text('Get statistics'),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: SizedBox.expand(
                child: Container(
                  color: Colors.white30,
                  child: const Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
      bottomSheet: _settingsVisible ? querySettings(context) : null,
    );
  }

  // The build method for the query options shown in the bottom sheet.
  Widget querySettings(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(
        20.0,
        20.0,
        20.0,
        max(
          20.0,
          View.of(context).viewPadding.bottom /
              View.of(context).devicePixelRatio,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text(
                'Query Settings',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              const Spacer(),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => setState(() => _settingsVisible = false),
              ),
            ],
          ),
          Row(
            children: [
              Checkbox(
                value: _onlyCitiesInCurrentExtent,
                onChanged: (value) =>
                    setState(() => _onlyCitiesInCurrentExtent = value!),
              ),
              const Text('Only cities in current extent'),
            ],
          ),
          Row(
            children: [
              Checkbox(
                value: _onlyCitiesGreaterThan5M,
                onChanged: (value) =>
                    setState(() => _onlyCitiesGreaterThan5M = value!),
              ),
              const Text('Only cities greater than 5M'),
            ],
          ),
        ],
      ),
    );
  }

  // Called when the map view is ready.
  void onMapViewReady() {
    // Add the statistic definitions for the 'POP' (Population) field.
    for (final type in StatisticType.values) {
      _statisticDefinitions.add(
        StatisticDefinition(
          onFieldName: 'POP',
          statisticType: type,
        ),
      );
    }
    // Create a map with a topographic basemap.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISTopographic);

    // Create a feature layer from the service feature table.
    final featureLayer = FeatureLayer.withFeatureTable(_serviceFeatureTable);

    // Add the feature layer to the map.
    map.operationalLayers.add(featureLayer);
    // Set the map to the map view.
    _mapViewController.arcGISMap = map;
    setState(() => _ready = true);
  }

  // Query statistics from the service feature table.
  void queryStatistics() async {
    // Create a statistics query parameters object.
    final statisticsQueryParameters =
        StatisticsQueryParameters(statisticDefinitions: _statisticDefinitions);

    // Set the geometry and spatial relationship if the flag is true.
    if (_onlyCitiesInCurrentExtent) {
      statisticsQueryParameters.geometry = _mapViewController.visibleArea;
      statisticsQueryParameters.spatialRelationship =
          SpatialRelationship.intersects;
    }
    // Set the where clause if the flag is true.
    if (_onlyCitiesGreaterThan5M) {
      statisticsQueryParameters.whereClause = 'POP_RANK = 1';
    }
    // Query the statistics.
    final statisticsQueryResult = await _serviceFeatureTable.queryStatistics(
      statisticsQueryParameters,
    );

    // Prepare the statistics results for display.
    final statistics = [];
    final records = statisticsQueryResult.statisticRecords();
    for (final record in records) {
      record.statistics.forEach((key, value) {
        final displayName =
            key.toLowerCase() == 'count_pop' ? 'CITY_COUNT' : key;
        final displayValue = key.toLowerCase() == 'count_pop'
            ? value.toStringAsFixed(0)
            : value.toStringAsFixed(2);
        statistics.add('[$displayName]  $displayValue');
      });
    }
    // Display the statistics in a dialog.
    if (mounted) {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(
              'Statistical Query Results',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            content: Text(statistics.join('\n')),
          );
        },
      );
    }
  }
}

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