页面异步通讯 PubSub
如果使用 Flet 创建聊天应用,需要在会话之间传递用户消息。当用户发送消息时,需要将消息广播到所有其他应用会话并显示在其页面上。
Flet 提供了一种简单的内置 PubSub 机制,用于在页面会话之间进行异步通信。
Flet PubSub 允许将消息广播到所有应用会话,或仅发送给特定的“主题”(或“频道”)订阅者。
典型的 PubSub 用法如下:
- 在应用会话启动时,订阅以广播消息,或订阅主题。
- 在某个事件(如“发送”按钮点击)上,发送广播消息,或发送给主题。
- 在某个事件(如“离开”按钮点击)上,取消订阅广播消息,或取消订阅主题。
- 在
page.on_close
上,取消订阅全部内容。
下面是一个简单聊天应用的示例:
import flet as ft
def main(page: ft.Page):
page.title = "Flet 聊天"
# 订阅广播消息
def on_message(msg):
messages.controls.append(ft.Text(msg))
page.update()
page.pubsub.subscribe(on_message)
def send_click(e):
page.pubsub.send_all(f"{user.value}: {message.value}")
# 清空表单
message.value = ""
page.update()
messages = ft.Column()
user = ft.TextField(hint_text="您的姓名", width=150)
message = ft.TextField(hint_text="您的消息...", expand=True) # 填充所有空间
send = ft.ElevatedButton("发送", on_click=send_click)
page.add(messages, ft.Row(controls=[user, message, send]))
ft.app(target=main, view=ft.AppView.WEB_BROWSER)
