Buscar pacotes, repositórios e categorias de apps

Detalhes do pacotev0.4.0

path_to_regexp

Converte um caminho como '/user/:id' em uma expressão regular.

AndroidiOSWebmacOSWindowsLinux
Downloads em 30 dias
73,4 mil
Curtidas
46
Pontos Pub
160

Instalar pacote

flutter pub add path_to_regexp

Visão geral do pacote

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

Um pacote Dart que converte padrões de caminho como '/user/:id' em expressões regulares para correspondência de rota. Ele permite a análise dinâmica de caminhos ao suportar captura de parâmetros, curingas e segmentos opcionais. Ideal para construir sistemas de roteamento em aplicativos Flutter, oferece uma solução leve para corresponder URLs a rotas definidas. O pacote é compatível com todas as principais plataformas e se integra perfeitamente à lógica de navegação existente.

Casos de uso

  • Correspondência de rota dinâmica
  • Análise de padrão de URL
  • Implementação do sistema de navegação
  • Extração de parâmetros de rota
  • Desenvolvimento de roteador personalizado
  • Correspondência de endpoint da API

Principais recursos

  • Suporta parâmetros nomeados (por exemplo, :id)
  • Gerencia segmentos opcionais
  • Inclui correspondência de curinga
  • Gera objetos RegExp reutilizáveis
  • Leve e rápido
  • Compatibilidade multiplataforma

Indicado para

  • Desenvolvedores construindo roteadores personalizados
  • Aplicativos que precisam de roteamento de URL flexível
  • Navegação de frontend com caminhos dinâmicos
  • Análise de padrões de rota complexos
  • Integração com bibliotecas de roteamento existentes

Considerações

  • Não manipula parâmetros de consulta
  • Sem suporte de middleware embutido
  • Requer resolução manual de rota
  • Limitado à correspondência de nível de caminho
  • Não projetado para uso completo como servidor HTTP

README original

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

path_to_regexp

Pub Travis

Converts a path such as /user/:id into a regular expression.

Matching

pathToRegExp() converts a path specification into a regular expression that matches conforming paths.

final regExp = pathToRegExp('/user/:id');
regExp.hasMatch('/user/12'); // => true
regExp.hasMatch('/user/alice'); // => true
Custom Parameters

By default, parameters match anything until the next delimiter. This behavior can be customized by specifying a regular expression in parentheses following a parameter name.

final regExp = pathToRegExp(r'/user/:id(\d+)');
regExp.hasMatch('/user/12'); // => true
regExp.hasMatch('/user/alice'); // => false
Extracting Parameters

Parameters can be extracted from a path specification during conversion into a regular expression.

final parameters = <String>[];
final regExp = pathToRegExp('/user/:id', parameters: parameters);
parameters; // => ['id']
Extracting Arguments

extract() maps the parameters of a path specification to their corresponding arguments in a match.

final parameters = <String>[];
final regExp = pathToRegExp('/user/:id', parameters: parameters);
final match = regExp.matchAsPrefix('/user/12');
extract(parameters, match); // => {'id': '12'}

Generating

pathToFunction() converts a path specification into a function that generates matching paths.

final toPath = pathToFunction('/user/:id');
toPath({'id': '12'}); // => '/user/12'

Tokens

parse() converts a path specification into a list of tokens, which can be used to create a regular expression or path generating function.

final tokens = parse('/users/:id');
final regExp = tokensToRegExp(tokens);
final toPath = tokensToFunction(tokens);

Similar to pathToRegExp(), parameters can also be extracted during parsing.

final parameters = <String>[];
final tokens = parse('/users/:id', parameters: parameters);

If you intend to match and generate paths from the same path specification, parse() and the token-based functions should be preferred to their path-based counterparts. This is because the token-based functions can reuse the same tokens, whereas each path-based function must parse the path specification anew.

Options

Prefix Matching

By default, a regular expression created by pathToRegExp or tokensToRegExp matches the entire input. However, if the optional prefix argument is true, it may also match as a prefix until a delimiter.

final regExp = pathToRegExp('/user/:id', prefix: true);
regExp.hasMatch('/user/12/details'); // => true
Case Sensitivity

By default, a regular expression created by pathToRegExp or tokensToRegExp is case sensitive. To create a case insensitive regular expression, set caseSensitive to false.

final regExp = pathToRegExp('/user/:id', caseSensitive: false);
regExp.hasMatch('/USER/12'); // => true

Demo

Try the path_to_regexp_demo to experiment with this library.

Credit

This package is heavily inspired by its JavaScript namesake path-to-regexp.

Categorias

Repositório-fonte

Projetos que usam este pacote