Buscar pacotes, repositórios e categorias de apps

Detalhes do pacotev2.2.0

string_similarity

Encontra o grau de similaridade entre duas strings com base no Coeficiente de Dice, que é geralmente melhor do que a distância de Levenshtein.

AndroidiOSWebmacOSWindowsLinux
Downloads em 30 dias
79,9 mil
Curtidas
129
Pontos Pub
160

Instalar pacote

flutter pub add string_similarity

Visão geral do pacote

Orientação gerada a partir de informações públicas. Apenas para referência.

O pacote string_similarity calcula o grau de similaridade entre duas strings usando o Coeficiente de Dice, um método geralmente mais preciso e rápido que a distância de Levenshtein. É ideal para tarefas como correspondência aproximada, correção de digitação e detecção de duplicatas em dados textuais. O algoritmo avalia os bigramas compartilhados entre as strings para produzir uma pontuação de similaridade de 0 (nenhum match) a 1 (match exato). Esta utilidade leve suporta todas as principais plataformas, incluindo Android, iOS, Web, macOS, Windows e Linux, tornando-a versátil para aplicações multiplataforma que exigem comparação eficiente de strings.

Casos de uso

  • Pesquisa difusa na entrada do usuário
  • Detectando entradas de texto quase duplicadas
  • Sugestões de correção automática
  • Deduplicação de dados
  • Correspondência de nomes de produtos entre fontes
  • Correção ortográfica

Principais recursos

  • Utiliza o Coeficiente de Dice para precisão
  • Desempenho rápido em comparação com Levenshtein
  • Compatibilidade multiplataforma
  • API simples com pontuações claras de similaridade
  • Gerencia comparações sem diferenciação de maiúsculas e minúsculas
  • Suporta caracteres não-ingleses

Indicado para

  • aplicativos de processamento de texto
  • Funcionalidades de busca e autocomplete
  • fluxos de trabalho de limpeza de dados
  • Validação de entrada para o usuário
  • Aplicações que precisam de correspondência rápida de strings

Considerações

  • Melhor para strings de curta a média duração
  • Não otimizado para textos muito longos
  • Não suporta correspondência parcial de palavras
  • Limitado à comparação de string para string
  • Nenhuma manipulação interna de palavras-chave ou stemming

README original

Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.

string_similarity

pub package license: MIT

A fast, dependency-free Dart package for measuring the similarity between two strings with the Sørensen–Dice coefficient.

Use it for fuzzy search, spelling suggestions, duplicate detection, and ranking the closest match from a list.

✨ Why string_similarity?

  • Simple extension methods and static methods
  • Scores from 0.0 (completely different) to 1.0 (identical)
  • Best-match search with individual ratings and the winning index
  • No runtime dependencies
  • Works on every platform supported by Dart and Flutter

📦 Installation

dart pub add string_similarity

Then import the package:

import 'package:string_similarity/string_similarity.dart';

🚀 Compare two strings

final score = 'healed'.similarityTo('sealed');

print(score); // 0.8

The equivalent static method is:

final score = StringSimilarity.compareTwoStrings('healed', 'sealed');

🏆 Find the best match

final result = 'healed'.bestMatch([
  'edward',
  'sealed',
  'theatre',
]);

print(result.bestMatch.target); // sealed
print(result.bestMatch.rating); // 0.8
print(result.bestMatchIndex); // 1

Every candidate and its score remain available in result.ratings.

The equivalent static method is:

final result = StringSimilarity.findBestMatch(
  'healed',
  ['edward', 'sealed', 'theatre'],
);

🧠 How it works

The package compares adjacent character pairs (bigrams) using the Sørensen–Dice coefficient. Whitespace is removed before comparison. Letter case and diacritics are kept, so Cote, cote, and côte are different values.

🔡 Case-insensitive comparison

Normalize both strings before comparing them:

final score = 'DART'.toLowerCase().similarityTo('dart'.toLowerCase());

print(score); // 1.0

🧩 Available methods

API Returns Description
value.similarityTo(other) double Compares two nullable strings.
value.bestMatch(targets) BestMatch Rates every nullable target and selects the best one.
StringSimilarity.compareTwoStrings(first, second) double Static alternative to similarityTo.
StringSimilarity.findBestMatch(value, targets) BestMatch Static alternative to bestMatch.

BestMatch provides:

  • ratings: every target and its score
  • bestMatch: the highest-rated target
  • bestMatchIndex: the winning target's original index

⚙️ Behavior and edge cases

Input Result
Two identical values, including null or '' 1.0
Only one value is null or empty 0.0
Different values where either has fewer than two characters 0.0
Several targets share the highest score The first one wins
The target list is empty Throws ArgumentError

🔎 Comparison details

  • Whitespace is ignored, but punctuation is not.
  • Comparison is case-sensitive and diacritic-sensitive.
  • The algorithm works on UTF-16 code units rather than grapheme clusters, so some emoji and combined Unicode characters may not behave like visible characters.
  • Sørensen–Dice measures shared bigrams. It is not a drop-in replacement for edit-distance algorithms such as Levenshtein distance.

📄 License

Licensed under the permissive MIT License.

Categorias

Repositório-fonte

Projetos que usam este pacote