0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

flet ページ切り替え (decorator)

Last updated at Posted at 2024-06-27

最初は flet-easyを使おうとしたけど
page.theme_mode がページ上で変更できなかったり (見つけてないだけかも)
fs.Datasy が使いにくかったので、fletだけで作ろうと思い
flet-easyの構文が好きだったので作りました

easy_app.py
import flet as ft

class EasyApp():
  def __init__(self, route_init="/"):
    self.route_init = route_init
    self.route_list = []
    self.ft_page = None
    self._custom_wrapper_befor = None
    self._custom_wrapper_after = None
  
  def custom_wrapper_befor(self, func):
    self._custom_wrapper_befor = func
  def custom_wrapper_after(self, func):
    self._custom_wrapper_after = func
  
  def route_change(self, e):
    for func, route, title in self.route_list:
      if e.route == route:
        if self.ft_page.controls: self.ft_page.controls.pop()
        self.ft_page.title = title
        if self._custom_wrapper_befor: self._custom_wrapper_befor(self.ft_page)
        func(self.ft_page)
        if self._custom_wrapper_after: self._custom_wrapper_after(self.ft_page)
        self.ft_page.update()
  
  def page(self, route="/", title=""):
    def decorator(func):
      self.route_list.append((func, route, title))
    return decorator
  
  def use(self, func=None, route="/", title=""):
    self.route_list.append((func, route, title))
  
  def main(self, page: ft.Page):
    self.ft_page = page
    page.on_route_change = self.route_change
    page.go(self.route_init)

  def run(self, *args):
    ft.app(target=self.main, *args)

使い方

page/Test.py
def Test(page: ft.page):
  pass
app.py
import flet as ft
from lib.easy_app import EasyApp #ここは変えてね

app = EasyApp(route_init="/home")

@app.page(route="/home", title="home")
def home_page(page: ft.page):
  page.add(ft.FilledButton("これはホームページです。", on_click=lambda e: page.go("/next")))

@app.page(route="/next", title="next")
def next_page(page: ft.page):
  page.add(ft.FilledButton("これは次のページです。", on_click=lambda e: page.go("/home")))

from pages import Test
app.use(Test, route="/test", title="test")

app.run()

余談

def befor_anim(page: ft.page):
  # fade outアニメーション
custom_wrapper_befor(befor_anim)

みたいにアニメーションつけてもいいかも

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?