Python Flet Tutorial: Build Cross-Platform Applications Effortlessly

Flet is an open-source Python library that simplifies building interactive user interfaces (UIs) for web, desktop, and mobile platforms. It allows developers to create multi-platform applications without dealing with complex front-end frameworks.

Flet wraps Flutter under the hood, enabling Python developers to utilize Flutter’s powerful UI capabilities seamlessly.

Codemagnet is here with this tutorial, which will help you explore how to get started with Flet, build a basic application, and dive into its key components with practical coding examples.

First of all let us some key features which this open source python library provide

Key Features of Flet

  1. Cross-Platform: Build apps that run on web browsers, desktops, and mobile devices.
  2. Declarative UI: Design UIs with a straightforward and Pythonic syntax.
  3. State Management: Easy-to-use state handling for interactive applications.
  4. No Front-End Knowledge Required: Focus solely on Python without needing to learn JavaScript, HTML, or CSS.

Installing Flet

To get started, you need to install Flet. It can be installed using pip:

pip install flet

Once installed, you’re ready to create your first application!

Let us building a Basic Flet Application

A common example to start with – “Hello World”

import flet as ft

def main(page: ft.Page):
    page.title = "Hello Flet!"
    page.add(ft.Text("Hello, World!"))

# Run the app
ft.app(target=main)

Output:

Explanation

  1. flet.Page: Represents the application window or browser page.
  2. page.title: Sets the title of the application.
  3. page.add(): Adds UI components (widgets) to the page.
  4. ft.Text: Displays text in the application.

Run the script, and a window will appear with the message “Hello, World!”.

Key Concepts in Flet

1. Widgets

Widgets are the building blocks of a Flet application. Common widgets include Text, Button, TextField, and ListView.

Example: Adding Multiple Widgets

import flet as ft

def main(page: ft.Page):
    page.title = "Interactive Widgets"
    page.add(
        ft.Text("Welcome to Flet!"),
        ft.TextField(label="Enter your name"),
        ft.ElevatedButton(text="Click Me!", on_click=lambda e: page.add(ft.Text("Button Clicked!")))
    )

ft.app(target=main)

Output:

Explanation

  • ft.TextField: A text input field with a label.
  • ft.Button: A clickable button. The on_click parameter specifies an event handler that runs when the button is clicked.

Layouts

Flet offers layouts like Column, Row, and Stack to organize widgets in your application.

Example: Using Column and Row Layouts

import flet as ft

def main(page: ft.Page):
    page.title = "Layouts Example"
    page.add(
        ft.Row([
            ft.Text("Row Item 1"),
            ft.Text("Row Item 2"),
        ]),
        ft.Column([
            ft.Text("Column Item 1"),
            ft.Text("Column Item 2"),
        ])
    )

ft.app(target=main)

Output:

Explanation

  • ft.Row: Aligns widgets horizontally.
  • ft.Column: Aligns widgets vertically.
  • Widgets are passed as a list inside Row or Column.

State Management

State management in Flet is straightforward, enabling the development of dynamic and interactive applications.

Example: Counter App

import flet as ft

def main(page: ft.Page):
    counter = ft.Text("0", size=30)
    
    def increment(e):
        counter.value = str(int(counter.value) + 1)
        page.update()

    page.title = "Counter App"
    page.add(
        counter,
        ft.ElevatedButton(text="Increment", on_click=increment)
    )

ft.app(target=main)

Output:

Explanation

  1. Stateful Widgets: The counter widget’s value changes dynamically.
  2. page.update(): Updates the UI after modifying the state.

Navigation

Flet supports multi-page navigation for building complex applications.

Example: Multi-Page App

import flet as ft

def main(page: ft.Page):
    def navigate_to_next_page(e):
        page.clean()
        page.add(ft.Text("Welcome to Page 2!"))
        page.update()

    page.title = "Navigation Example"
    page.add(
        ft.Text("Page 1"),
        ft.ElevatedButton(text="Go to Page 2", on_click=navigate_to_next_page)
    )

ft.app(target=main)

Output:

Explanation

  • page.clean(): Clears the current page content.
  • Dynamic Navigation: Switch between pages by modifying the page content.

Now, that you have understood some features of Flet. Let us build a to do application

Building a To-Do Application

Now, let’s build a simple To-Do application that demonstrates adding, displaying, and removing tasks.

Full Code:

import flet as ft

def main(page: ft.Page):
    page.title = "To-Do App"

    tasks = ft.Column()

    def add_task(e):
        task_name = task_input.value
        if task_name:
            # Create a task row with a unique remove button
            task_row = ft.Row([
                ft.Text(task_name),
                ft.ElevatedButton("Remove", on_click=lambda e, tn=task_name: remove_task(tn))
            ])
            tasks.controls.append(task_row)
            task_input.value = ""
            page.update()

    def remove_task(task_name):
        # Keep only tasks that don't match the task_name to remove
        tasks.controls = [task for task in tasks.controls if task.controls[0].value != task_name]
        page.update()

    task_input = ft.TextField(label="New Task")
    page.add(
        task_input,
        ft.ElevatedButton("Add Task", on_click=add_task),
        tasks
    )

ft.app(target=main)

Output:

Let us add some innovation to the above code:

import flet as ft

def main(page: ft.Page):
    page.title = "My Beautiful To-Do App"
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.padding = 20

    tasks = ft.Column(spacing=10, scroll=ft.ScrollMode.AUTO)

    def add_task(e):
        task_name = task_input.value.strip()
        if task_name:
            task_row = ft.Container(
                content=ft.Row(
                    controls=[
                        ft.Text(task_name, expand=True, size=16),
                        ft.ElevatedButton(
                            "✔ Done",
                            on_click=lambda e, tn=task_name: remove_task(tn),
                            bgcolor=ft.colors.GREEN,
                            color=ft.colors.WHITE,
                        ),
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                bgcolor=ft.colors.AMBER_100,
                border_radius=10,
                padding=10,
                margin=ft.margin.only(bottom=5),
            )
            tasks.controls.append(task_row)
            task_input.value = ""
            page.update()

    def remove_task(task_name):
        tasks.controls = [
            task for task in tasks.controls
            if task.content.controls[0].value != task_name
        ]
        page.update()

    task_input = ft.TextField(
        label="Enter your task",
        expand=True,
        autofocus=True,
    )
    add_button = ft.ElevatedButton(
        "Add Task",
        on_click=add_task,
        icon=ft.icons.ADD,
        bgcolor=ft.colors.BLUE,
        color=ft.colors.WHITE,
    )

    page.add(
        ft.Text(
            "📝 My To-Do List",
            size=24,
            weight=ft.FontWeight.BOLD,
            color=ft.colors.BLUE_900,
        ),
        ft.Row(
            controls=[task_input, add_button],
            alignment=ft.MainAxisAlignment.CENTER,
            spacing=10,
        ),
        ft.Divider(),
        tasks,
    )

ft.app(target=main)

Output:

Its not yet over yet !

Let us see another example

import flet as ft
from datetime import datetime

def main(page: ft.Page):
    page.title = "Mood Tracker"
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.padding = 20

    mood_history = ft.Column(spacing=10, scroll=ft.ScrollMode.AUTO)

    def add_mood(e):
        selected_mood = mood_dropdown.value
        if selected_mood:
            # Create a new mood entry
            mood_entry = ft.Container(
                content=ft.Row(
                    controls=[
                        ft.Text(
                            f"{selected_mood} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                            expand=True,
                            size=16,
                        ),
                        ft.IconButton(
                            icon=ft.icons.DELETE,
                            icon_color=ft.colors.RED,
                            tooltip="Remove entry",
                            on_click=lambda _: remove_entry(mood_entry),
                        ),
                    ],
                    alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
                ),
                bgcolor=ft.colors.LIGHT_BLUE_100,
                border_radius=10,
                padding=10,
                margin=ft.margin.only(bottom=5),
            )
            mood_history.controls.append(mood_entry)
            mood_dropdown.value = None
            page.update()

    def remove_entry(entry):
        mood_history.controls.remove(entry)
        page.update()

    def clear_history(e):
        mood_history.controls.clear()
        page.update()

    # Mood selection dropdown
    mood_dropdown = ft.Dropdown(
        label="Select your mood",
        options=[
            ft.dropdown.Option("😊 Happy"),
            ft.dropdown.Option("😢 Sad"),
            ft.dropdown.Option("😡 Angry"),
            ft.dropdown.Option("😌 Relaxed"),
            ft.dropdown.Option("😎 Confident"),
            ft.dropdown.Option("🤔 Thoughtful"),
        ],
        width=300,
    )

    # Add mood button
    add_mood_button = ft.ElevatedButton(
        "Add Mood",
        on_click=add_mood,
        bgcolor=ft.colors.GREEN,
        color=ft.colors.WHITE,
        icon=ft.icons.ADD,
    )

    # Clear history button
    clear_history_button = ft.ElevatedButton(
        "Clear History",
        on_click=clear_history,
        bgcolor=ft.colors.RED,
        color=ft.colors.WHITE,
        icon=ft.icons.DELETE_SWEEP,
    )

    # Page layout
    page.add(
        ft.Text(
            "🌈 Mood Tracker",
            size=24,
            weight=ft.FontWeight.BOLD,
            color=ft.colors.BLUE_900,
        ),
        ft.Text("Track your daily mood and maintain a history.", size=14, italic=True),
        ft.Divider(),
        ft.Row(
            controls=[mood_dropdown, add_mood_button],
            alignment=ft.MainAxisAlignment.CENTER,
            spacing=10,
        ),
        ft.Divider(),
        ft.Text("Mood History:", size=18, weight=ft.FontWeight.BOLD),
        mood_history,
        ft.Divider(),
        clear_history_button,
    )

ft.app(target=main)

Output:

Flet emerges as a powerful and user-friendly framework for building cross-platform applications with Python. Its ability to combine Python’s simplicity with the visual and interactive features of web and desktop apps makes it a highly versatile tool for developers. Throughout this tutorial, we explored how Flet simplifies the app development process by allowing you to design modern, responsive UIs without the need for extensive frontend expertise.

Key Takeaways:

  1. Ease of Use: Flet’s intuitive API enables developers to create feature-rich applications quickly. You can focus more on logic and functionality without worrying about the underlying complexity of traditional frontend technologies.
  2. Cross-Platform Compatibility: With Flet, the same codebase can run seamlessly across web, desktop, and mobile platforms, making it ideal for projects requiring a wide reach.
  3. Interactive Components: Flet’s built-in widgets such as TextField, Button, Column, and more, empower developers to create interactive and engaging user interfaces with minimal effort.
  4. Dynamic UI Updates: Features like real-time updates and event handling make Flet a great choice for building applications that need to react to user interactions instantly.
  5. Flexibility and Customization: Whether it’s designing a simple to-do app, a mood tracker, or a fully-fledged dashboard, Flet provides extensive customization options, enabling you to tailor the application to your specific requirements.

Why Choose Flet for Your Next Project?

  • Developer-Friendly: No prior knowledge of HTML, CSS, or JavaScript is required, making it accessible for Python developers.
  • Time-Efficient: The straightforward design process and pre-built components speed up application development.
  • Future-Proof: Flet’s cross-platform capabilities mean your app is ready for deployment across multiple devices without extra effort.

Whether you’re a beginner exploring GUI development or an experienced developer looking for a Python-based alternative to traditional frontend frameworks, Flet offers an effortless way to build polished, professional-grade applications. As you continue your journey with Flet, the possibilities are endless—from creating productivity tools to visually stunning apps for business and personal use.

Now that you’re equipped with the basics of Flet, it’s time to dive deeper, experiment with its features, and turn your ideas into fully functional, cross-platform applications!

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>