getDropdownData method
Fetch dropdown data from a Dynamics 365 entity.
Parameters:
entity - The target data entity name (e.g., Customers, Items).
valueField - The field name to be used as the unique key (e.g., "CustomerAccount").
displayField - The field name to be shown in the dropdown (e.g., "Name").
filterByField - (Optional) A field name used for filtering results.
filterValue - (Optional) The value to filter by.
Returns:
A List<Map<String, String>> where each map contains:
- "key" : the unique identifier of the record.
- "value" : the display name of the record.
Notes:
- Removes duplicates by converting the list to a Set, then back to a List.
- Throws an exception if the API request fails.
- Requires a valid access token from
getAccessToken().
Implementation
Future<List<Map<String, String>>> getDropdownData({
required String entity,
required String valueField,
required String displayField,
String? filterByField,
String? filterValue,
}) async {
final token = await getAccessToken();
if (token == null) return [];
final uri = (filterByField != null &&
filterByField.isNotEmpty &&
filterValue != null &&
filterValue.isNotEmpty)
? Uri.parse(
"$resource/data/$entity?\$filter=$filterByField eq '$filterValue'")
: Uri.parse("$resource/data/$entity");
try {
final response = await http.get(
uri,
headers: {
'Authorization': 'Bearer $token',
'Accept': 'application/json',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final entities = data['value'] as List;
return entities
.map<Map<String, String>>((e) {
final key = e[valueField]?.toString() ?? '';
final name = e[displayField]?.toString() ?? '';
return {"key": key, "value": name};
})
.toSet()
.toList();
} else {
throw Exception(
'❌ Failed to fetch $entity: ${response.statusCode}\n${response
.body}',
);
}
} catch (e) {
print('❗ Exception during getDropdownData: $e');
rethrow;
}
}