addTag method

void addTag(
  1. bool duplicate,
  2. String tag,
  3. BuildContext? context
)

Adds a new tag to the tag list.

Performs comprehensive validation including:

  • Empty tag checking
  • Duplicate validation (based on duplicate parameter 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 operation
  • tag: The tag string to add
  • context: The optional BuildContext for showing error messages (can be null in tests)

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) {
      if (context != null) {
        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!) {
    if (context != null) {
      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) {
      if (context != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(validationError)),
        );
      }
      return;
    }
  }

  _tags.add(processedTag);
  notifyListeners();

  widget.onTagAdded?.call(processedTag);
  widget.onTagsChanged?.call(_tags);
}