Skip to main content

Flet Stacked v2.0.0

Stacked is a custom Flet control for managing multiple routes with smooth, animated transitions. Navigate by key or index, walk route order (go_next/go_prev), or use browser-style history (go_back/go_forward). Routes can be plain controls or lazy factories, navigation can be vetoed by async guards, and transitions can differ by direction — all backed by ft.AnimatedSwitcher.

Features

  • Smooth transitions — every switch is animated by ft.AnimatedSwitcher; duration, curve and transition type are fully customizable per instance.
  • Direction-aware animation — use one transition for forward navigation (SCALE, SLIDE, …) and another for going back (FADE, …); Stacked picks the right one automatically.
  • Flexible navigation — switch by key or index, walk route order with go_next / go_prev, or use browser-style history with go_back / go_forward and a configurable max_history.
  • Lazy routes with params — register a zero-arg factory (or a factory that accepts **params) instead of an eager control. Pass params={"user_id": 42} to switch() and the factory receives them.
  • Async guards — an on_before_leave(from_route, to_route) callback can veto navigation. If it's async, use the *_async navigation methods (the sync ones raise a clear RuntimeError).
  • Rich route events — on_route_change receives a RouteChangeEvent with from_route, to_route, direction, source, params, and previous/current indices.
  • Dynamic routes — add_route, remove_route, rename_route, and set_routes keep history and the current route consistent.
  • Full async API — switch_async, go_async, go_next_async, go_prev_async, go_back_async, go_forward_async.
  • Rich introspection — current_route, current_control, history, forward_history, can_go_back, can_go_forward, can_go_next, can_go_prev, has_route, get_route_keys, plus len(), in, and iteration support.

Installation

Install from the source

pip install git+https://github.com/osamalzabidi/flet-stacked.git

Install from PyPi

pip install flet-stacked

Requires Python 3.12+ and Flet 1.1+.

Quick start

import flet as ft
from flet_stacked import Stacked


def main(page: ft.Page):
    page.title = "Flet Stacked"

    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.window.width = page.window.height = 600

    routes = {
        "home": ft.Text("Home Page", size=30),
        "about": ft.Text("About Page", size=30),
        "contact": ft.Text("Contact Page", size=30),
    }

    stacked = Stacked(
        routes,
        index="home",
        on_route_change=lambda event: print(event),   # "home → about [switch]"
    )

    page.add(
        stacked,
        ft.Row(
            [
                ft.Button("About", on_click=lambda e: stacked.switch("about")),
                ft.Button("Next", on_click=lambda e: stacked.go_next()),
                ft.Button("Prev", on_click=lambda e: stacked.go_prev()),
            ],
            alignment=ft.MainAxisAlignment.CENTER,
        ),
    )


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

Output of the above code

Example 2

Advanced features

Browser-style history

back    = ft.IconButton(ft.Icons.ARROW_BACK,    disabled=True)
forward = ft.IconButton(ft.Icons.ARROW_FORWARD, disabled=True)

stacked = Stacked(routes, index="home", max_history=30)

def on_change(event):
    back.disabled    = not stacked.can_go_back()
    forward.disabled = not stacked.can_go_forward()
    page.update()

back.on_click    = lambda e: page.run_task(stacked.go_back_async)
forward.on_click = lambda e: page.run_task(stacked.go_forward_async)

go_back() pops the bounded _history stack; go_forward() re-applies routes you walked away from. Call clear_history() to reset both stacks.

Lazy routes with parameters

def user_page(user_id: int = 0, **_):
    return ft.Column([ft.Text(f"User #{user_id}", size=28)])

stacked = Stacked(
    {"home": ft.Text("Home", size=30), "user": user_page},
    index="home",
    cache_lazy_routes=False,   # fresh control per visit
)

page.run_task(stacked.switch_async, "user", params={"user_id": 42})

With cache_lazy_routes=True (the default), factory-produced controls are cached, so returning to a route restores the same instance and its state. Set force=True on switch to bypass the cache for a single call.

Async guards

async def guard(from_route: str, to_route: str) -> bool:
    if from_route == "editor" and editor_is_dirty():
        return await confirm_discard()
    return True

stacked = Stacked(routes, index="home", on_before_leave=guard)

# All navigation must go through the async API:
page.run_task(stacked.switch_async, "settings")
page.run_task(stacked.go_back_async)

Returning False from the guard cancels navigation and leaves the current route untouched. Sync def guards work with both APIs; async def guards require the *_async methods.

Direction-aware transitions

stacked = Stacked(
    routes,
    index="home",
    forward_transition=ft.AnimatedSwitcherTransition.SCALE,   # go_next / go_forward
    backward_transition=ft.AnimatedSwitcherTransition.FADE,   # go_prev / go_back
)

Stacked infers direction from the source (go_next, go_back, …) or from the positional indices of the routes. Pass direction="forward" | "backward" | "replace" explicitly to override.

Rich route events

from flet_stacked import RouteChangeEvent

def on_change(event: RouteChangeEvent):
    print(
        f"{event.from_route!r} -> {event.to_route!r} "
        f"dir={event.direction} source={event.source} "
        f"params={event.params}"
    )

RouteChangeEvent fields:

Field Type Description
from_route str | None Previous route name (None on first render).
to_route str Route being navigated to.
direction "initial" | "forward" | "backward" | "replace" Inferred or explicit direction.
source str One of "switch", "go", "go_next", "go_prev", "go_back", "go_forward", "add_route", "remove_route", "set_routes".
params dict Passed through from switch(..., params=...).
previous_index int | None Index of from_route.
current_index int | None Index of to_route.

Dynamic routes

stacked.add_route("new_tab", factory, switch_to=True)
stacked.rename_route("new_tab", "renamed_tab")
stacked.remove_route("renamed_tab", fallback="home")
stacked.set_routes({...}, fallback="home")

All four keep _history, _forward_stack, the resolved cache, and the current route consistent — if the current route is removed, Stacked switches to fallback (or the first remaining route) automatically.

Examples

Example What it shows
examples/package_browser.py Grid → detail navigation with switch_async(params=...), direction-aware transitions, and a header driven by RouteChangeEvent.
examples/flip_card.py Visa / Mastercard / Amex cards that flip on tap — each card wraps a small Stacked whose face is swapped at the 90° point of the flip animation.
examples/guarded_form.py Unsaved-changes confirmation dialog wired through an async on_before_leave guard.
examples/dynamic_tabs.py Add / close tabs with add_route and remove_route.

API reference

Stacked(routes, index=0, *, ...)

Parameter Type Default Description
routes dict[str, ft.Control | Callable] — Route name → control or factory.
index str | int 0 Initial route (name or positional int).
on_route_change Callable[[RouteChangeEvent], ...] None Called after every successful transition. May be async.
on_before_leave Callable[[str, str], bool | Awaitable[bool]] None Guard: return False to veto.
max_history int 50 Bounded history for go_back. 0 disables history.
cache_lazy_routes bool True Cache factory-produced controls.
forward_transition ft.AnimatedSwitcherTransition | None None Used for go_next / go_forward.
backward_transition ft.AnimatedSwitcherTransition | None None Used for go_prev / go_back.
**kwargs Forwarded to ft.AnimatedSwitcher. Defaults: FADE, 150 ms in, 50 ms out, LINEAR / EASE_IN_CUBIC curves.

Navigation

Method Sync / Async Returns
switch(route, *, params=None, source="switch", direction=None, record_history=True, force=False) sync (name, control)
switch_async(...) async (name, control)
go(route, **kw) / go_async(route, **kw) both (name, control)
go_next(**kw) / go_next_async(**kw) both (name, control) | None
go_prev(**kw) / go_prev_async(**kw) both (name, control) | None
go_back(**kw) / go_back_async(**kw) both (name, control) | None
go_forward(**kw) / go_forward_async(**kw) both (name, control) | None

Introspection

Method Returns
current_route() str
current_index() int
current_control() ft.Control
history() tuple[str, ...]
forward_history() tuple[str, ...]
can_go_back() / can_go_forward() bool
can_go_next() / can_go_prev() bool
has_route(route) bool
get_route_keys() tuple[str, ...]
get_routes() dict[str, RouteSource]
get_route(route, default=None) RouteSource | None
len(stacked), route in stacked, for r in stacked —

Mutation

Method Description
add_route(key, source, *, position=None, switch_to=False) Register a new route, optionally switching to it.
remove_route(key, *, fallback=None) Remove a route; navigates to fallback if it was current.
rename_route(old, new) Rename in place, preserving history and current route.
set_routes(routes, *, fallback=None) Replace the route table; navigates to fallback if the current route disappears.
clear_history() Clear both history and forward stacks.
refresh_current() Re-resolve the current route (fresh factory call) and re-render.

Migrating from v1.2.0

  1. on_route_change signature changed. It now receives a RouteChangeEvent instead of (route, *args, **kwargs):

    # before
    on_route_change=lambda route, *a, **k: print(route)
    # after
    on_route_change=lambda event: print(event.to_route)
    
  2. go_back() is now history pop, not an alias for go_prev(). Use go_prev() for route-order navigation.

  3. current_control() returns the resolved control (from a factory if applicable), not the raw entry in routes.

  4. Unknown routes raise KeyError at construction and on switch, rather than silently setting content=None.

  5. set_routes auto-navigates to fallback (or the first route) when the current route is removed, keeping the switcher consistent.

Contributing

Pull requests and suggestions are welcome! Open an issue first to discuss any major changes.

License

Apache-2.0

Metadata

Release files for flet-stacked 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flet-stacked 1.2.0
File Size Uploaded Provenance Actions
flet_stacked-1.2.0.tar.gz 17.7 kB With provenance Details for flet_stacked-1.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flet-stacked 1.2.0
File Interpreter ABI Platform Actions
flet_stacked-1.2.0-py3-none-any.whl Python 3 none any Details for flet_stacked-1.2.0-py3-none-any.whl

Total release size: 31.7 kB

Release files / flet_stacked-1.2.0.tar.gz

Download URL flet_stacked-1.2.0.tar.gz
Size 17.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b9a0ee75d234ff54aa35679ed36caef01630e66940964dffe15b5323f0956bc5
BLAKE2b-256 checksum
How to use checksums
3410ea44363972dea5f164ff9813cbe76c8bf7ebb77762123ca8cf18dc971d88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Release files / flet_stacked-1.2.0-py3-none-any.whl

Download URL flet_stacked-1.2.0-py3-none-any.whl
Size 13.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b2627d4cf43357a9c2e172e7957f0a16ad2d303fb1e229d2c3148298381dd664
BLAKE2b-256 checksum
How to use checksums
3be5d358898ba013a30a235a8cc43a12c8b298111d9106d5e7598d5c6f81cbfd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

Security for flet-stacked 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for flet_stacked-1.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page