addTag method
Adds a new tag to the tag list.
Performs comprehensive validation including:
- Empty tag checking
- Duplicate validation (based on
duplicateparameter and widget settings) - Maximum tag limit enforcement
- Custom tag validation using TagField.tagValidator
If validation fails, shows appropriate error messages via ScaffoldMessenger. On successful addition, notifies listeners and triggers callbacks.
Parameters:
duplicate: Whether to allow duplicate tags for this operationtag: The tag string to addcontext: The BuildContext for showing error messages
Example:
notifier.addTag(false, 'flutter', context);
Implementation
void addTag(bool duplicate, String tag, BuildContext context) {
if (tag.isEmpty) return;
String processedTag = _processTag(tag);
if (processedTag.isEmpty) return;
// Check for duplicates
if (!duplicate && _isDuplicate(processedTag)) {
if (!widget.allowDuplicates) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Duplicate tags are not allowed')),
);
return;
}
// If duplicates are allowed, proceed without further checks
}
// Check max tags limit
if (widget.maxTags != null && _tags.length >= widget.maxTags!) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Maximum tag limit reached')),
);
return;
}
// Validate tag
if (widget.tagValidator != null) {
final validationError = widget.tagValidator!(processedTag);
if (validationError != null) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(validationError)));
return;
}
}
_tags.add(processedTag);
notifyListeners();
widget.onTagAdded?.call(processedTag);
widget.onTagsChanged?.call(_tags);
}