Flutter富文本编辑插件quill_native_bridge的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter富文本编辑插件quill_native_bridge的使用

插件介绍

quill_native_bridge 是一个内部的Flutter插件,用于 flutter_quill 包访问平台特定的API。该插件提供了多种功能,如获取剪贴板中的HTML、将HTML复制到剪贴板、从系统相册中打开图片等。

功能列表

以下是 quill_native_bridge 的一些主要功能及其在不同平台上的支持情况:

功能 iOS Android macOS Windows Linux Web
isIOSSimulator
getClipboardHtml
copyHtmlToClipboard
copyImageToClipboard
getClipboardImage
getClipboardGif
getClipboardFiles
openGalleryApp
saveImageToGallery
saveImage
  • : 该功能在此平台上不适用或不支持。
  • : 插件当前未实现该功能。
  • : 支持并可正常工作。

使用示例

以下是一个完整的示例代码,展示了如何使用 quill_native_bridge 插件进行富文本编辑的相关操作:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:quill_native_bridge/quill_native_bridge.dart';

// 创建一个全局实例,允许在测试中覆盖
QuillNativeBridge quillNativeBridge = QuillNativeBridge();

void main() => runApp(const MainApp());

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Quill Native Bridge'),
        ),
        body: const SingleChildScrollView(
          child: Center(child: Buttons()),
        ),
      ),
    );
  }
}

class Buttons extends StatelessWidget {
  const Buttons({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton.icon(
          onPressed: () => _onButtonPressed(
            QuillNativeBridgeFeature.isIOSSimulator,
            context: context,
          ),
          label: const Text('Is iOS Simulator'),
          icon: const Icon(Icons.apple),
        ),
        ElevatedButton.icon(
          onPressed: () => _onButtonPressed(
            QuillNativeBridgeFeature.getClipboardHtml,
            context: context,
          ),
          label: const Text('Get HTML from Clipboard'),
          icon: const Icon(Icons.html),
        ),
        ElevatedButton.icon(
          onPressed: () => _onButtonPressed(
            QuillNativeBridgeFeature.copyHtmlToClipboard,
            context: context,
          ),
          label: const Text('Copy HTML to Clipboard'),
          icon: const Icon(Icons.copy),
        ),
        // 其他按钮类似...
      ],
    );
  }
}

Future<void> _onButtonPressed(
  QuillNativeBridgeFeature feature, {
  required BuildContext context,
}) async {
  final scaffoldMessenger = ScaffoldMessenger.of(context);
  final isFeatureUnsupported = !(await quillNativeBridge.isSupported(feature));

  switch (feature) {
    case QuillNativeBridgeFeature.isIOSSimulator:
      if (isFeatureUnsupported) {
        scaffoldMessenger.showText(
          kIsWeb
              ? "Can't check if the device is an iOS simulator on the web."
              : 'Available only on iOS to determine if the device is a simulator.',
        );
        return;
      }
      final result = await quillNativeBridge.isIOSSimulator();
      scaffoldMessenger.showText(result
          ? "You're running the app on iOS simulator."
          : "You're running the app on a real iOS device.");
      break;
    case QuillNativeBridgeFeature.getClipboardHtml:
      if (isFeatureUnsupported) {
        scaffoldMessenger.showText(
          kIsWeb
              ? 'Retrieving HTML from the clipboard is currently not supported on the web.'
              : 'Retrieving HTML from the clipboard is currently not supported on ${defaultTargetPlatform.name}.',
        );
        return;
      }
      final result = await quillNativeBridge.getClipboardHtml();
      if (result == null) {
        scaffoldMessenger
            .showText('The HTML is not available on the clipboard.');
        return;
      }
      scaffoldMessenger.showText('HTML from the clipboard: $result');
      debugPrint('HTML from the clipboard: $result');
      break;
    case QuillNativeBridgeFeature.copyHtmlToClipboard:
      if (isFeatureUnsupported) {
        scaffoldMessenger.showText(
          kIsWeb
              ? 'Copying HTML to the clipboard is not supported on the web.'
              : 'Copying HTML to the clipboard is not supported on ${defaultTargetPlatform.name}.',
        );
        return;
      }
      const html = '''
          <strong>Bold text</strong>
          <em>Italic text</em>
          <u>Underlined text</u>
          <span style="color:red;">Red text</span>
          <span style="background-color:yellow;">Highlighted text</span>
        ''';
      await quillNativeBridge.copyHtmlToClipboard(html);
      scaffoldMessenger.showText('HTML copied to the clipboard: $html');
      break;
    // 其他case类似...
  }
}

extension ScaffoldMessengerX on ScaffoldMessengerState {
  void showText(String text, {SnackBarAction? action}) {
    clearSnackBars();
    showSnackBar(SnackBar(content: Text(text), action: action));
  }
}

平台设置

某些功能需要特定平台的配置,例如在Android平台上使用 copyImageToClipboard 需要更新 AndroidManifest.xml 文件并创建 file_paths.xml 文件。

Android 设置
  1. 更新 AndroidManifest.xml

    <manifest>
        <application>
            ...
            <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="${applicationId}.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true" >
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/file_paths" />
            </provider>
            ...
        </application>
    </manifest>
    
  2. 创建 file_paths.xml

    <paths>
        <cache-path name="cache" path="." />
    </paths>
    
iOS 设置

保存图片到相册时需要权限设置,具体步骤如下:

  1. 打开 ios/Runner/Info.plist 文件并添加以下键:
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>Your description here</string>
    
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Your description here</string>
    

更多关于Flutter富文本编辑插件quill_native_bridge的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter富文本编辑插件quill_native_bridge的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用quill_native_bridge插件来实现富文本编辑的代码示例。quill_native_bridge是一个用于Flutter的插件,它结合了Quill富文本编辑器与原生平台(iOS和Android)的功能,以提供高性能的富文本编辑体验。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加quill_native_bridge及其依赖项:

dependencies:
  flutter:
    sdk: flutter
  quill_flutter: ^3.0.0  # 确保版本与quill_native_bridge兼容
  quill_native_bridge: ^0.x.x  # 替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置iOS和Android

由于quill_native_bridge依赖于原生代码,你需要进行一些原生平台配置。

iOS

ios/Podfile中,确保你有以下配置来启用Swift和Objective-C的互操作性:

platform :ios, '10.0'

# ...

target 'Runner' do
  use_frameworks!
  config = use_native_modules!

  # ...

  # Flutter Pod
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '5.0'  # 或更高版本
    end
  end
end

Android

通常,quill_native_bridge的Android配置是自动处理的,但你可能需要确保你的android/app/build.gradle文件中的compileSdkVersiontargetSdkVersion是最新的。

3. 使用QuillNativeBridge

在你的Flutter代码中,你可以这样使用quill_native_bridge

import 'package:flutter/material.dart';
import 'package:quill_flutter/quill_flutter.dart';
import 'package:quill_native_bridge/quill_native_bridge.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Quill Native Bridge Example'),
        ),
        body: QuillNativeBridgeExample(),
      ),
    );
  }
}

class QuillNativeBridgeExample extends StatefulWidget {
  @override
  _QuillNativeBridgeExampleState createState() => _QuillNativeBridgeExampleState();
}

class _QuillNativeBridgeExampleState extends State<QuillNativeBridgeExample> {
  late QuillController _controller;

  @override
  void initState() {
    super.initState();
    _controller = QuillController(
      document: Document(),
      selection: TextSelection.collapsed(offset: 0),
    )..addListener(() {
        // 监听文档变化,可以在这里处理保存等操作
      });
  }

  @override
  Widget build(BuildContext context) {
    return QuillEditor(
      controller: _controller,
      focusNode: FocusNode(),
      readOnly: false,
      padding: EdgeInsets.all(16.0),
      scrollPhysics: BouncingScrollPhysics(),
      placeholder: 'Compose an epic...',
      customStyles: QuillStyles(
        // 自定义样式
      ),
      customFormats: QuillFormats(
        // 自定义格式
      ),
      expands: false,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个使用quill_native_bridge支持的Quill编辑器。请注意,quill_native_bridge本身主要用于性能优化和原生功能集成,而上述代码主要展示了如何在Flutter中使用Quill编辑器。如果你需要利用quill_native_bridge提供的特定原生功能(如文件导入/导出、图像粘贴等),你可能需要查阅该插件的官方文档以获取更多详细信息和高级用法。

由于quill_native_bridge的API可能会随着版本更新而变化,建议查阅最新的quill_native_bridge GitHub仓库或pub.dev页面以获取最新信息和示例代码。

回到顶部