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

패키지 상세v3.0.14

clipboard

텍스트, 리치 텍스트(HTML), 이미지 지원이 있는 Flutter 클립보드.

AndroidiOSmacOSWindows
30일 다운로드
13.2만
좋아요
644
Pub 점수
160

패키지 설치

flutter pub add clipboard

패키지 개요

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

클립보드 패키지는 플러터 개발자에게 Android, iOS, macOS 및 Windows에서 텍스트, 리치 텍스트(HTML), 이미지 데이터를 지원하는 시스템 클립보드에 원활하게 액세스할 수 있도록 제공합니다. 클립보드에서 읽고 쓰는 기능을 가능하게 하여 형식이 지정된 콘텐츠나 미디어를 다루는 앱의 복사/붙여넣기 기능에 이상적입니다. 이 패키지는 플러터 생태계와 원활하게 통합되며, samuelezedi.com에서 유지 관리됩니다. 오픈소스 성격으로 인해 커뮤니티 기여와 투명성이 보장됩니다.

사용 사례

  • 앱 간에 형식이 지정된 텍스트 복사
  • 리치 텍스트 에디터에 HTML 콘텐츠 붙여넣기
  • 클립보드를 통해 이미지 공유
  • 클립보드로 복사 버튼 구현
  • Flutter와 네이티브 앱 간 데이터 전송

주요 기능

  • 일반 텍스트 및 HTML 지원
  • 이미지 데이터를 처리합니다
  • 크로스 플랫폼 호환성
  • 읽기/쓰기 작업을 위한 간단한 API
  • 오픈소스, 공개 저장소

적합한 대상

  • 풍부한 텍스트 복사가 필요한 앱
  • 콘텐츠 에디터를 개발하는 개발자
  • 시스템 클립보드와 데이터를 교환해야 하는 도구
  • 크로스플랫폼 데스크톱 및 모바일 앱

고려 사항

  • 일부 시스템에서는 플랫폼별 권한이 필요합니다
  • 이미지 처리는 플랫폼에 따라 다를 수 있습니다
  • 시스템 클립보드 범위로 제한
  • 내장된 기록 관리 없음
  • 하위 OS 클립보드 동작에 따라 다릅니다

원본 README

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

Enhanced Flutter Clipboard

pub package

A super-power clipboard package for Flutter, with text, Rich text (HTML), and image support.

GitHub

Screenshots

Screenshot 1 Screenshot 2 Screenshot 3 Screenshot 4

Features

  • ✅ Basic Copy/Paste: Simple text copying and pasting
  • ✅ True Rich Text Support: Native HTML clipboard support via platform channels
  • ✅ Image Support: Copy and paste images to/from clipboard (PNG format)
  • ✅ Multiple Formats: Copy multiple data formats simultaneously (text, HTML, images)
  • ✅ Native Clipboard Monitoring: Real-time clipboard change detection using platform APIs
  • ✅ Error Handling: Comprehensive error handling with custom exceptions and error codes
  • ✅ Utility Methods: Check clipboard status, size, and content type
  • ✅ Callback Support: Success and error callbacks for operations
  • ✅ Debug Information: Get detailed clipboard debugging info
  • ✅ Cross-Platform: Works on Android, iOS, Web, and Windows with graceful fallbacks
  • ✅ Null Safety: Full null safety support
  • ✅ Memory Safe: Proper listener management with cleanup mechanisms
  • ✅ Production Ready: Battle-tested with comprehensive error handling

Installation

Add this to your package's pubspec.yaml file:

dependencies:
  clipboard: ^3.0.14

Platform Setup

Android

The package uses platform channels for enhanced features. No additional setup required - the package automatically falls back to Flutter's built-in Clipboard API if platform channels are unavailable.

iOS

No additional setup required. The package automatically handles platform channel registration.

Web

Fully supported with automatic fallback to browser Clipboard API.

Windows

No additional setup required. The package uses native Windows API with GDI+ for image support. Platform channels are automatically registered.

Basic Usage

import 'package:clipboard/clipboard.dart';
Copy to clipboard
// Basic copy
await FlutterClipboard.copy('Hello Flutter friends');

// Copy with error handling
try {
  await FlutterClipboard.copy('Hello World');
  print('Text copied successfully!');
} on ClipboardException catch (e) {
  print('Copy failed: ${e.message}');
}
Paste from clipboard
// Basic paste
String text = await FlutterClipboard.paste();

// Paste with error handling
try {
  String text = await FlutterClipboard.paste();
  setState(() {
    myTextField.text = text;
  });
} on ClipboardException catch (e) {
  print('Paste failed: ${e.message}');
}

Advanced Features

Rich Text Support
// Copy rich text with HTML
await FlutterClipboard.copyRichText(
  text: 'Hello World',
  html: '<b>Hello</b> <i>World</i>',
);

// Paste rich text
EnhancedClipboardData data = await FlutterClipboard.pasteRichText();
print('Text: ${data.text}');
print('HTML: ${data.html}');
Multiple Format Copy
// Copy multiple formats simultaneously
await FlutterClipboard.copyMultiple({
  'text/plain': 'Hello World',
  'text/html': '<b>Hello World</b>',
  'image/png': imageBytes, // Uint8List of PNG image
  'custom/format': 'Custom data',
});
Image Copy/Paste
import 'dart:typed_data';
import 'package:flutter/services.dart';

// Copy image to clipboard
final ByteData imageData = await rootBundle.load('assets/image.png');
final Uint8List imageBytes = imageData.buffer.asUint8List();
await FlutterClipboard.copyImage(imageBytes);

// Paste image from clipboard
final Uint8List? pastedImage = await FlutterClipboard.pasteImage();
if (pastedImage != null) {
  // Use the image bytes (e.g., display in Image.memory)
  Image.memory(pastedImage);
}

// Images are also included in pasteRichText()
final data = await FlutterClipboard.pasteRichText();
if (data.hasImage) {
  print('Clipboard contains image: ${data.imageBytes?.length} bytes');
}
Callback Support
// Copy with success/error callbacks
await FlutterClipboard.copyWithCallback(
  text: 'Hello World',
  onSuccess: () {
    print('Copy successful!');
    showSnackBar('Text copied to clipboard');
  },
  onError: (error) {
    print('Copy failed: $error');
    showSnackBar('Copy failed: $error');
  },
);
Clipboard Monitoring
// Add clipboard change listener (returns cleanup function)
void onClipboardChanged(EnhancedClipboardData data) {
  print('Clipboard changed: ${data.text}');
}

// Add listener and get cleanup function
final removeListener = FlutterClipboard.addListener(onClipboardChanged);

// Start native monitoring (uses platform APIs when available)
await FlutterClipboard.startMonitoring(interval: Duration(milliseconds: 500));

// Stop monitoring
await FlutterClipboard.stopMonitoring();

// Remove listener (or use the returned cleanup function)
FlutterClipboard.removeListener(onClipboardChanged);
// Or: removeListener();

// Remove all listeners at once
FlutterClipboard.removeAllListeners();
Utility Methods
// Check if clipboard has content
bool hasData = await FlutterClipboard.hasData();

// Check if clipboard is empty
bool isEmpty = await FlutterClipboard.isEmpty();

// Get clipboard content type
ClipboardContentType type = await FlutterClipboard.getContentType();

// Get clipboard data size
int size = await FlutterClipboard.getDataSize();

// Validate input before copying
bool isValid = FlutterClipboard.isValidInput('Hello World');

// Clear clipboard
await FlutterClipboard.clear();
Debug Information
// Get comprehensive debug information
Map<String, dynamic> debugInfo = await FlutterClipboard.getDebugInfo();
print(debugInfo);
// Output: {
//   'hasData': true,
//   'contentType': 'ClipboardContentType.text',
//   'dataSize': 11,
//   'listenersCount': 2,
//   'isMonitoring': true,
//   'lastData': 'Hello World'
// }

EnhancedClipboardData Class

The EnhancedClipboardData class provides rich information about clipboard content:

EnhancedClipboardData data = await FlutterClipboard.pasteRichText();

// Check content types
if (data.hasText) print('Has text: ${data.text}');
if (data.hasHtml) print('Has HTML: ${data.html}');
if (data.hasImage) print('Has image: ${data.imageBytes?.length} bytes');
if (data.hasFiles) print('Has file paths: ${data.filePaths}');

// Check if completely empty
if (data.isEmpty) print('Clipboard is empty');

// Get timestamp
print('Copied at: ${data.timestamp}');

Error Handling

The package provides custom exceptions for better error handling:

try {
  await FlutterClipboard.copy('');
} on ClipboardException catch (e) {
  print('Error: ${e.message}');
  print('Error code: ${e.code}');
}

Common error codes:

  • EMPTY_TEXT: Attempted to copy empty text
  • COPY_ERROR: General copy operation failed
  • PASTE_ERROR: General paste operation failed
  • EMPTY_CONTENT: No content provided for rich text copy
  • EMPTY_FORMATS: No formats provided for multiple format copy

Content Types

The ClipboardContentType enum provides information about clipboard content:

ClipboardContentType type = await FlutterClipboard.getContentType();

switch (type) {
  case ClipboardContentType.text:
    print('Plain text content');
    break;
  case ClipboardContentType.html:
    print('HTML content');
    break;
  case ClipboardContentType.mixed:
    print('Mixed content (text + HTML)');
    break;
  case ClipboardContentType.empty:
    print('Empty clipboard');
    break;
  case ClipboardContentType.unknown:
    print('Unknown content type');
    break;
}

Legacy Methods

For backward compatibility, the original methods are still available:

// Legacy methods (still supported)
bool success = await FlutterClipboard.controlC('Hello World');
dynamic data = await FlutterClipboard.controlV();

Testing

The package includes comprehensive testing utilities:

// Set mock data for testing
await FlutterClipboard.setMockData('Test data');

// Get debug information for testing
Map<String, dynamic> info = await FlutterClipboard.getDebugInfo();

Why This Enhanced Package?

I originally built this package 4 years ago for basic clipboard functionality. Over time, I realized developers needed more advanced features:

  • True Rich Text Support: Native HTML clipboard support via platform channels (not just in-memory storage)
  • Native Monitoring: Real-time clipboard change detection using platform APIs (Android clipboard listeners, iOS notifications)
  • Better Error Handling: Proper exceptions with error codes for better debugging
  • Utility Methods: Check clipboard status, content type, and data size
  • Debug Support: Comprehensive debugging information
  • Memory Safe: Proper listener management prevents memory leaks
  • Production Ready: Graceful fallbacks ensure reliability across all platforms
  • Modern API: Updated to latest Dart/Flutter standards with platform channel support

This enhanced version maintains backward compatibility while adding powerful new features that modern Flutter apps need. The package now uses platform channels for true multi-format support and native clipboard monitoring, with automatic fallbacks to Flutter's built-in Clipboard API when needed.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Follow Me

카테고리

의존성

의존성 목록 1 개

소스 저장소

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