Flutter操作系统粘贴板Clipboard

背景

有时候我们需要执行一些复制粘贴操作,Flutter 提供了Clipboard跟ClipboardData用来操作系统的复制粘贴。

使用起来非常简单

import 'package:flutter/services.dart';
Clipboard.setData(ClipboardData(text: '复制的内容'));

这里有个bug,如果你把null赋值给剪贴板,ios就会出现系统崩溃问题,需要对null做下兼容。

2020-02-22 13:45:06.465678+0800 Runner[1003:243363] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIConcretePasteboard setString:]: Argument is not an object of type NSString [NSNull]'
*** First throw call stack:
(0x1a3feaa48 0x1a3d11fa4 0x1a3ee01c0 0x1a7f9aec8 0x1030964e4 0x10311442c 0x1030afdbc 0x103106654 0x1030bd9e8 0x1030c209c 0x1a3f6903c 0x1a3f68d78 0x1a3f68448 0x1a3f63584 0x1a3f62adc 0x1adf03328 0x1a807063c 0x102a2d614 0x1a3dec360)
libc++abi.dylib: terminating with uncaught exception of type NSException

提供获取粘贴板文本的方法

ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
print('data content ${data.text}'); //  data content 复制的内容

让我们来看下Clipboard实现的源代码

///设置要复制到粘贴板中的内容
@immutable
class ClipboardData {
  /// Creates data for the system clipboard.
  const ClipboardData({ this.text });

  /// Plain text variant of this clipboard data.
  final String text;
}

/// Utility methods for interacting with the system's clipboard.
///对粘贴板进行操作的类
class Clipboard {
  Clipboard._();

  // Constants for common [getData] [format] types.

  /// Plain text data format string.
  ///
  /// Used with [getData].
  static const String kTextPlain = 'text/plain';

  /// Stores the given clipboard data on the clipboard.
  ///将ClipboardData中的内容复制的粘贴板
  static Future setData(ClipboardData data) async {
    await SystemChannels.platform.invokeMethod(
      'Clipboard.setData',
      {
        'text': data.text,
      },
    );
  }

  /// Retrieves data from the clipboard that matches the given format.
  ///
  /// The `format` argument specifies the media type, such as `text/plain`, of
  /// the data to obtain.
  ///
  /// Returns a future which completes to null if the data could not be
  /// obtained, and to a [ClipboardData] object if it could.
  ///获得粘贴板中的内容,这是个异步的操作
  static Future getData(String format) async {
    final Map result = await SystemChannels.platform.invokeMethod(
      'Clipboard.getData',
      format,
    );
    if (result == null)
      return null;
    return ClipboardData(text: result['text']);
  }
}

你可能感兴趣的:(Flutter操作系统粘贴板Clipboard)