Buscar pacotes, repositórios e categorias de apps

Detalhes do pacotev0.1.0

span_builder

Facilita a criação de spans a partir de texto simples e fornece descarte automático de GestureRecognizers

Downloads em 30 dias
11
Curtidas
18
Pontos Pub
40

Instalar pacote

flutter pub add span_builder

Visão geral do pacote

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

SpanBuilder é um pacote Flutter/Dart projetado para simplificar a criação de trechos de texto rico a partir de texto simples, permitindo a fácil integração de texto formatado, links e elementos interativos. Ele gerencia automaticamente a liberação dos GestureRecognizers, evitando vazamentos de memória e melhorando o desempenho. Ideal para renderização dinâmica de texto com interações embutidas, como hashtags ou menções clicáveis. O pacote suporta uma sintaxe limpa e declarativa para criar layouts de texto complexos sem a necessidade de gerenciamento manual do ciclo de vida.

Casos de uso

  • Construindo texto rico interativo com elementos clicáveis
  • Renderização de texto formatado com estilos mistos
  • Criando analisadores de menção ou hashtag
  • Automatizando a limpeza do reconhecedor de gestos
  • Exibindo conteúdo dinâmico com ações embutidas

Principais recursos

  • Descarte automático do GestureRecognizer
  • Criação simples de span a partir de texto simples
  • Suporta formatação de texto rico
  • Reduz o código boilerplate
  • Evita vazamentos de memória

Indicado para

  • Desenvolvedores construindo interfaces de chat
  • Aplicativos com conteúdo de texto dinâmico
  • Projetos que exigem elementos de texto interativos
  • Equipes que priorizam código limpo e manutenção

Considerações

  • Limitado a componentes de interface baseados em texto
  • Sem suporte embutido para layouts complexos
  • Requer compreensão da estrutura do TextSpan
  • Não adequado para necessidades de renderização não-textual
  • Depende do ecossistema de widget Text do Flutter

README original

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

span_builder

Facilitates creation of spans from plain text and provides an automated disposal of GestureRecognizers.

Description

Given some plain text, e.g.: "The quick brown fox" allows you to apply multiple spans at multiple positions. Positions can be specified by a matching word (whereText), e.g. "brown" and/or range from=10, to=15. Spans are subclasses of InlineSpan. If the span you are trying to apply is TextSpan you don't need to pass whereText as it will be inferred from text within the provided span.

Once you are done using SpanBuilder, use build() to return calculated list of spans. Spans can't overlap.

Usage:
final spans = SpanBuilder("The quick brown fox")
  .apply(TextSpan(text: "brown", style: TextStyle(fontWeight: FontWeight.bold)))
  .apply(TextSpan(text: "🦊"), whereText: "fox")
  .build()

From there you can use these spans in your RichText, e.g.:

RichText(
  text: TextSpan(children: spans)
)

If you plan to make your text "tappable" read on.

Handling GestrueRecognizer (text taps)

If you try passing GestrueRecognizer as a field in TextSpan it will get stripped away - HERE IS WHY.

TL;DR: We don't want to leak GestureRecognizer but TextSpan has no idea about the lifecycle of Widget so you need a stateful widget to keep a reference to the recognizer untill you're done with it. Sounds like a mess, right?

The workaround is to provide a builder for the recognizer like this:

apply(TextSpan(text: "jumps"),
  recognizerBuilder: () => TapGestureRecognizer()..onTap = () {
    // your code here
  })

Then you can use this SpanBuilder together with SpanBuilderWidget which will manage creating and disposing of TapGestrueRecognizer at the right time:

SpanBuilderWidget(
  text: SpanBuilder("fox jumps")
    ..apply(TextSpan(text: "jumps"),
      recognizerBuilder: () => TapGestureRecognizer()..onTap = () {
        // your code here
      })
)

If you care only about onTap interaction you can use this API shortcut:

apply(TextSpan(text: "jumps"),
  onTap: () {
    // your code here
  }
)
Testing:

There are little resources on how to test RichText in general. For this reason there is helper testing library span_builder_test that can help you verify state of your spans in your UI tests.

void main() {
  testWidgets('MyApp test', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());

    final spanFinder = find.byKey(span_key);

    expect(spanFinder, findsOneWidget);
    final allSpans = tester.findSpans(spanFinder).length;
    expect(allSpans, 8);

    final foxSpans = tester.findSpans(spanFinder, predicate: (span) {
      return span is TextSpan && span.text == "🦊"; 
    });
    expect(foxSpans.length, 1);
  });
}

span_builder_test

WidgetTest helpers and extensions for testing span_builder

Getting Started

This is a companion library to the span_builder library intended to help you write test wherever that library is used.

Usage
Related Content

Categorias

Repositório-fonte

Projetos que usam este pacote

Ainda não há dados.