flutterdartclipboard

How to Copy Text with Custom Fonts (e.g., Baybayin Script) to Clipboard in Flutter?


I'm working on a Flutter app that transliterates text from the Latin script to Baybayin. The output is displayed using the Baybayin Neue font, and I want users to be able to copy this output in Baybayin and paste it into other apps while preserving the custom font style.

Currently, I'm using the Clipboard API in Flutter to copy the text. The text is copied correctly in the Baybayin script (Unicode), but when pasted into other apps, it appears in the system's default font, not in the Baybayin Neue font that I'm using in my app.

What I've Tried:

What I Need:

Is there any way to copy the text with the custom font style (Baybayin Neue) so that when the user pastes the text into another app (like a text editor or social media), it retains the Baybayin Neue font?

Possible Solutions I’ve Thought About:

  1. Copying as rich text or HTML/CSS for Flutter Web (but unsure how to implement this).
  2. Copying the text as an image (but it would lose the ability to be edited).

Is this something that can be done with Flutter, or would it need to be handled by a package or workaround? Any suggestions or insights would be appreciated!


Solution

  • Copying as Rich Text (HTML for Web): On Flutter Web, you can attempt to copy the text as HTML (with inline CSS for the font), which some web-based apps might respect. However, this won't work across all platforms. You can use a combination of Flutter Web's JS interop to handle rich text copying in the clipboard.

    Example:

    import 'dart:html' as html;
    
    void copyAsHtml(String text) {
     final html.TextAreaElement textArea = html.TextAreaElement();
     textArea.value = '<span style="font-family: \'Baybayin 
     Neue\';">$text</span>';
     html.document.body?.append(textArea);
     textArea.select();
     html.document.execCommand('copy');
     textArea.remove();
    }
    

    This approach tries to copy the text with an inline style, but it will only work where rich text pasting is supported, like some text editors or web apps.

    Alternatively, you can also use the universal_html package to achieve the same functionality