getTarget function
Implementation
String getTarget(WidgetRef ref) {
// The rolesProvider lists the roles for the different variables which we
// need to know for parsing the R scripts. Roles get updated when user
// updates the roles in the UI.
Map<String, Role> roles = ref.watch(rolesProvider);
// Extract the target variable from the rolesProvider.
String target = 'NULL';
roles.forEach((key, value) {
if (value == Role.target) {
target = key;
}
});
if (target == 'NULL') {
Map<String, dynamic> metaData = ref.watch(metaDataProvider);
String candidateTarget = 'NULL';
// Initialize minLevels to null initially.
int? minLevels;
// Iterate through metadata to find factor variables.
metaData.forEach((varName, varData) {
// Ensure varData is a Map and contains 'datatype' and 'unique'.
if (varData is Map &&
varData.containsKey('datatype') &&
varData.containsKey('unique')) {
String dataType = varData['datatype'].first ?? '';
dynamic uniqueData = varData['unique'];
// Check if it's a factor/categoric type.
if (dataType.contains('factor') ||
dataType.contains('character') ||
dataType.contains('ordered')) {
// Ensure 'unique' is a list and not empty.
if (uniqueData is List && uniqueData.isNotEmpty) {
// Attempt to parse the unique count.
int? uniqueCount = int.tryParse(uniqueData[0].toString());
if (uniqueCount != null) {
// If this is the first suitable variable found, initialize minLevels.
if (minLevels == null) {
minLevels = uniqueCount;
candidateTarget = varName;
} else {
// Otherwise, compare with the current minimum.
if (uniqueCount <= minLevels!) {
minLevels = uniqueCount;
candidateTarget = varName;
}
}
}
}
}
}
});
// Return the best candidate found from metadata, or 'NULL' if none.
// This replaces the stdout parsing logic.
if (candidateTarget != 'NULL' && roles[candidateTarget] != Role.ident) {
return candidateTarget;
}
}
// If target was already set by rolesProvider, return it here.
// If the metadata search above didn't find anything, 'NULL' is returned from there.
return target;
}