Skip to content

Share 继承自:Service, BaseControl

使用平台分享面板分享文本、链接或文件。

在 Web 应用中分享

浏览器只会在处理点击或按键期间打开分享面板, 而下面的方法无法满足这一要求 —— 当点击到达你的 Python 代码、指令又传回来时,权限已经失效。

改为使用 ShareText 动作,由客户端 在原始手势内部执行。参见 客户端动作。

通过客户端动作分享 ​

python
import flet as ft


def main(page: ft.Page):
    # `action` is performed by the client while it is still handling the click.
    # Browsers only open the share sheet during a gesture, so `Share()` called
    # from Python has no effect on the web.
    page.add(
        ft.SafeArea(
            content=ft.Column(
                controls=[
                    ft.Text("Share this page with someone:"),
                    ft.Button(
                        "Share",
                        icon=ft.Icons.SHARE,
                        action=ft.ShareText(
                            "Flet lets you build multi-platform apps in Python: "
                            "https://flet.dev",
                            subject="Flet",
                        ),
                    ),
                    ft.Text(
                        "The share sheet is a system dialog - what it offers "
                        "depends on the platform, and on desktop browsers it "
                        "may not be available at all."
                    ),
                ],
            ),
        )
    )


if __name__ == "__main__":
    ft.run(main)

示例 ​

python
import os

import flet as ft


async def main(page: ft.Page):
    share = ft.Share()

    status = ft.Text()
    result_raw = ft.Text()

    async def do_share_text():
        result = await share.share_text(
            "Hello from Flet!",
            subject="Greeting",
            title="Share greeting",
        )
        status.value = f"Share status: {result.status}"
        result_raw.value = f"Raw: {result.raw}"

    async def do_share_uri():
        result = await share.share_uri("https://flet.dev")
        status.value = f"Share status: {result.status}"
        result_raw.value = f"Raw: {result.raw}"

    async def do_share_files_from_bytes():
        file = ft.ShareFile.from_bytes(
            b"Sample content from memory",
            mime_type="text/plain",
            name="sample.txt",
        )
        result = await share.share_files(
            [file],
            text="Sharing a file from memory",
        )
        status.value = f"Share status: {result.status}"
        result_raw.value = f"Raw: {result.raw}"

    async def do_share_files_from_paths():
        if page.web:
            status.value = "File sharing from paths is not supported on the web."
            return
        #
        temp_dir = await ft.StoragePaths().get_temporary_directory()
        file_path = os.path.join(temp_dir, "sample_from_path.txt")
        with open(file_path, "wb") as f:
            f.write(b"Sample content from file path")

        result = await share.share_files(
            [ft.ShareFile.from_path(file_path)],
            text="Sharing a file from memory",
        )
        status.value = f"Share status: {result.status}"
        result_raw.value = f"Raw: {result.raw}"

    page.add(
        ft.SafeArea(
            ft.Column(
                [
                    ft.Row(
                        [
                            ft.Button("Share text", on_click=do_share_text),
                            ft.Button("Share link", on_click=do_share_uri),
                            ft.Button(
                                "Share file from bytes",
                                on_click=do_share_files_from_bytes,
                            ),
                            ft.Button(
                                "Share file from path",
                                on_click=do_share_files_from_paths,
                            ),
                        ],
                        wrap=True,
                    ),
                    status,
                    result_raw,
                ],
            )
        )
    )


if __name__ == "__main__":
    ft.run(main)

属性 ​

名称类型默认值说明
dataAnyskip_任意类型的自定义数据。
keyOptional['KeyValue']None用于在更新之间保持控件标识稳定的键。

只读属性 ​

名称类型默认值说明
parentOptional['BaseControl']—此控件的直接祖先(父级)。 默认为 None,只有在此控件被挂载(加入页面树)后才有值。 Page 控件(页面树的根)是个例外 —— 它的 parent 始终为 None。
page'Page'—此控件所属的页面。

方法 ​

名称类型默认值说明
share_textShareResult—分享纯文本,可选携带主题、标题和缩略图。 参数: text:要分享的文本。 title:分享面板的可选标题。 subject:所分享文本的可选主题。 preview_thumbnail:要在分享面板中显示的可选缩略图文件。 share_position_origin:分享面板的可选位置原点。 download_fallback_enabled:是否启用下载作为回退。 mail_to_fallback_enabled:是否启用 mailto 作为回退。 excluded_cupertino_activities:要排除的 iOS/macOS 活动可选列表。
share_uriShareResult—分享链接/URI。 参数: uri:要分享的 URI。 share_position_origin:分享面板的可选位置原点。 excluded_cupertino_activities:要排除的 iOS/macOS 活动可选列表。
share_filesShareResult—分享一个或多个文件,可选携带文本/元数据。 参数: files:要分享的 ShareFile 实例列表。 title:分享面板的可选标题。 text:随文件一起分享的可选文本。 subject:所分享文件的主题。 preview_thumbnail:要在分享面板中显示的可选缩略图文件。 share_position_origin:分享面板的可选位置原点。 download_fallback_enabled:是否启用下载作为回退。 mail_to_fallback_enabled:是否启用 mailto 作为回退。 excluded_cupertino_activities:要排除的 iOS/macOS 活动可选列表。
init———
is_isolated——返回此控件是否被标记为隔离。 隔离控件会被排除在父级驱动的更新遍历之外,并需要自行管理更新边界。
build——在控件初始化期间调用一次,用于定义其子控件。在此方法中 page 属性可用。
before_update——每当此控件被更新时都会调用此方法。 注意: 务必不要在此处调用或请求 update()。
before_event——在事件处理器执行之前拦截事件。 返回 False 可取消分发。返回 True 或 None 则继续正常的事件处理。
did_mount——在控件挂载到页面树之后调用。 重写此方法以启动需要已挂载页面的资源,例如订阅、定时器或服务监听器。
will_unmount——在控件从页面树移除之前调用。 重写此方法以释放 did_mount() 中创建的资源,例如订阅、定时器或外部句柄。
get_data_channel——解析为此 widget 在 Dart 侧分配的 [DataChannel]。模式: on_data_channel_open: Optional[ft.EventHandler[DataChannelOpenEvent]] = None def init(self): self.on_data_channel_open = self._on_open def _on_open(self, e): self._channel = self.get_data_channel(e.channel_id) 幂等 —— 底层的 Connection 会按 id 缓存 DataChannel,因此重复调用会返回同一实例。没有错误路径:该 id 始终来自框架触发的事件,所以当此方法运行时,通道在两端都已存在。
updateNone—为此控件请求一次 UI 更新。 在更改控件状态或属性后调用。控件必须已挂载到页面且未被标记为冻结。

关注我,学习大模型、大数据、Python等热门技术。