패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.7.3

selectable

포함된 모든 텍스트 위젯에서 텍스트 선택을 가능하게 하는 Flutter 위젯입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
2.1천
좋아요
80
Pub 점수
140

패키지 설치

flutter pub add selectable

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

선택 가능한 패키지는 포함된 모든 텍스트 위젯에서 텍스트 선택 기능을 향상시키는 Flutter 위젯입니다. 텍스트 요소를 감싸서 원활하고 일관된 텍스트 선택 동작을 가능하게 하며, 문서, 메모 또는 독서 인터페이스와 같은 상호작용이 필요한 텍스트 콘텐츠가 필요한 앱에 이상적입니다. 이 패키지는 Android, iOS, Web, macOS, Windows 및 Linux의 모든 주요 플랫폼에서 작동하여 일관된 기능을 보장합니다. 복잡한 사용자 정의 로직 없이 선택 가능한 텍스트 구현을 간소화합니다. 여러 텍스트 컴포넌트에 선택 기능을 추가할 수 있는 간단한 방법으로, 하나의 재사용 가능한 래퍼로 개발자를 위한 설계되었습니다.

사용 사례

  • 읽기 앱
  • 문서 편집기
  • 노트 작성 도구
  • 인터랙티브 튜토리얼
  • 텍스트 공유 기능

주요 기능

  • 일반 텍스트 선택
  • 크로스 플랫폼 지원
  • 여러 텍스트용 단일 래퍼
  • 간단한 통합
  • 일관된 선택 동작

적합한 대상

  • 텍스트 중심 앱을 개발하는 개발자
  • 다중 텍스트 선택이 필요한 앱
  • 크로스 플랫폼 요구 사항을 가진 프로젝트
  • 가독성에 중점을 둔 UI
  • 교육용 또는 콘텐츠가 풍부한 애플리케이션

고려 사항

  • 사용자 지정 선택 핸들에 대한 추가 스타일링이 필요할 수 있습니다
  • 텍스트 선택만 가능
  • 텍스트가 아닌 위젯에는 적합하지 않습니다
  • 큰 텍스트 블록과 성능 영향
  • 기반 플랫폼 텍스트 렌더링에 따라 다릅니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

selectable

Pub

A Flutter widget that enables text selection over all the text widgets it contains — with platform-adaptive selection handles and popup menu, a controller for listening to and programmatically changing the selection, and customizable menu items, selection color, and selection rendering.

Try it out at: https://ronjb.github.io/selectable

Note: This library predates Flutter's SelectableRegion and related classes. It continues to be maintained because it is used in production apps, but if Flutter's native selection support meets your needs, consider using it instead.

Features

  • Selection across all the text widgets contained in a Selectable — multiple Text and RichText widgets, spanning paragraphs.
  • Long-press (and optionally double-tap) a word to select it, then drag the selection handles to adjust the selection, with autoscroll when dragging near the top or bottom of a scrollable viewport.
  • Platform-adaptive selection controls and popup menu: Cupertino style on iOS and macOS, Material style elsewhere.
  • A default popup menu with Copy, Look Up, and Search Web items — localized using the ambient MaterialLocalizations/CupertinoLocalizations — and support for replacing or extending the menu with custom items.
  • A SelectableController for listening to selection changes and for programmatically selecting, deselecting, hiding, and showing the selection.
  • Customizable selection appearance via selectionColor, selection rect "rectifiers", and fully custom selection painters.
  • IgnoreSelectable for excluding subtrees from selection.

Getting started

Add selectable to your app's pubspec.yaml file:

dependencies:
  selectable: ^0.7.0

Requires Dart >=3.12.0 and Flutter >=3.44.0.

Material and Cupertino packages

As of 0.7.0, selectable uses the standalone material_ui and cupertino_ui packages instead of Flutter's in-framework material.dart and cupertino.dart libraries, which are moving out of the SDK (see Flutter's migration guide).

Your own code does not need to change, because selectable's public API exposes no Material or Cupertino types. The popup menu, however, gets its theme and its localized labels from material_ui and cupertino_ui, so your app has to provide them. If your app has migrated to those packages, this works as-is. If your app still imports package:flutter/material.dart, the popup menu throws No MaterialLocalizations found.

If your app has not migrated yet, you can stay on the 0.6.x line, which continues to use Flutter's in-framework libraries:

dependencies:
  selectable: ^0.6.7

Or you can provide material_ui's theme and localizations around your Selectable:

import 'package:material_ui/material_ui.dart' as mui;

Localizations(
  locale: Localizations.localeOf(context),
  delegates: mui.GlobalMaterialLocalizations.delegates,
  child: mui.Theme(
    // Configure this to match your app's theme.
    data: mui.ThemeData(),
    child: Selectable(child: myContent),
  ),
)

Note that MaterialUiCompatibilityBridge does not help here: it maps a migrated app's theme back to the in-framework libraries, which is the opposite direction.

Usage

Import the package:

import 'package:selectable/selectable.dart';

And wrap the widgets you want to enable text selection for in a Selectable:

Scaffold(
  body: SingleChildScrollView(
    child: Selectable(
      child: Column(
        children: [
          Text('... a lot of text ...'),
          // ... more widgets of any type that might contain text ...
        ],
      ),
    ),
  ),
)

Important: If a scrollable widget (such as SingleChildScrollView, ListView, or CustomScrollView) is used to wrap the text widgets you want to enable selection for, the Selectable widget must be a descendant of the scrollable widget and an ancestor of the text widgets.

Scrollables and app bars

If the Selectable is in a scrollable, pass the scrollable's ScrollController to the Selectable as well. It is used to autoscroll when a selection handle is dragged near the top or bottom of the viewport, and to keep the popup menu positioned in the visible area. If part of the viewport is covered by an overlay, such as a pinned app bar, set topOverlayHeight to its height:

Selectable(
  scrollController: _scrollController,
  topOverlayHeight: kToolbarHeight + MediaQuery.paddingOf(context).top,
  child: child,
)
Selection gestures

Long-pressing a word selects it. To also enable double-tapping a word to select it, set selectWordOnDoubleTap to true:

Selectable(
  selectWordOnDoubleTap: true,
  child: child,
)
Excluding widgets from selection

Wrap widgets that shouldn't be selectable in IgnoreSelectable:

IgnoreSelectable(
  child: Text('This text is not selectable.'),
)
Customizing the popup menu

Selectable shows a popup menu with Copy, Look Up, and Search Web items by default. The default item titles are localized using the ambient MaterialLocalizations (or CupertinoLocalizations). To customize the menu, pass in popupMenuItems. For example, to show the default Copy item along with a custom item that shows the selected text in a dialog:

Selectable(
  popupMenuItems: [
    const SelectableMenuItem(type: SelectableMenuItemType.copy),
    SelectableMenuItem(
      title: 'Show It',
      isEnabled: (controller) => controller!.isTextSelected,
      handler: (controller) {
        showDialog<void>(
          context: context,
          builder: (context) => AlertDialog(
            content: Text(controller!.getSelection()!.text!),
          ),
        );
        return true;
      },
    ),
  ],
  child: child,
)

Menu items can also have an icon, and custom menu builders can resolve the localized default title for a built-in item type with defaultTitleForMenuItemType.

Using a SelectableController

Pass a SelectableController to the Selectable to listen to selection changes and to work with the selection programmatically:

final _selectionController = SelectableController();

// In the widget tree:
Selectable(
  selectionController: _selectionController,
  child: child,
)

// Listen for selection changes.
_selectionController.addListener(() {
  if (_selectionController.isTextSelected) {
    print('Selected text: ${_selectionController.getSelection()!.text}');
  }
});

The controller supports, among other things:

// Select programmatically.
_selectionController.selectAll();
_selectionController.selectWordAtIndex(100);
_selectionController.selectWordsBetweenIndexes(100, 200);

// Deselect.
_selectionController.deselect();

// Hide and show the selection (e.g. while a dialog is showing),
// with an optional fade animation duration.
_selectionController.hide();
_selectionController.unhide();

// Get the combined text of all the text widgets contained in the
// Selectable (useful with the index-based select methods above), or
// just its length.
final text = _selectionController.getContainedText();
final length = _selectionController.containedTextLength;

The Selection object returned by getSelection() includes the selected text, the global startIndex and endIndex of the selection, and the selection rectangles. Remember to dispose the controller when it is no longer needed.

Customizing the selection appearance

The selection color can be set with the selectionColor parameter. How the raw rectangles of selected text are converted into the displayed selection rects can be customized with a "rectifier" — for example, to merge the per-line rects into, at most, three contiguous rects:

_selectionController.setCustomRectifier(SelectionRectifiers.merged);

or provide your own List<Rect> Function(List<Rect>). For full control over how the selection is drawn, implement a custom SelectionPainter and set it with _selectionController.setCustomPainter (see example/lib/my_selection_painter.dart).

Additional information

The example app demonstrates most of these features, including advanced use cases such as updating the style of the selected text spans.

Feel free to file an issue to ask questions or report problems: https://github.com/ronjb/selectable/issues

카테고리

의존성

의존성 목록 7 개

소스 저장소

이 패키지를 사용하는 프로젝트