In Flet, the concept of View plays a central role. A View is the top-level container that encompasses all other controls within an application. When a new user session starts, a root view is automatically created.

From a layout perspective, a View is essentially a Column-type control. This means it shares the same behavior and many of the properties of the Column control.

View Properties

Some of the most common properties available in a View include:

  • appbar: Defines the app bar.

  • bgcolor: Specifies the background color of the view.

  • controls: Contains the controls present in the view.

  • horizontal_alignment: Defines the horizontal alignment of the content.

  • padding: Spacing between the page content and its edges.

Configuring Padding

By default, a page's padding property is set to 10 pixels on each side. However, you can modify this as needed.

Example: Set Padding to Zero

page.padding = 0
page.update()

Managing Controls in the View

Controls within a View can be dynamically added, removed, or manipulated during application runtime.

Adding a New Control

To add a control, such as text, to the page, you can use append:

page.controls.append(ft.Text("Hello!"))
page.update()

Or use the shortcut method add, which is more straightforward:

page.add(ft.Text("Hello!"))

Removing the Top Control

To remove the topmost (last added) control from the page:

page.controls.pop()
page.update()

Practical Example: Managing Controls in a View

Let's create a simple example to illustrate how to manipulate controls within a View.

import flet as ft

def main(page: ft.Page):
    page.title = "View Example in Flet"
    page.padding = 20

    def add_text(e):
        page.add(ft.Text("New text added!"))

    def remove_text(e):
        if len(page.controls) > 0:
            page.controls.pop()
            page.update()

    # Adding buttons to manipulate controls
    page.add(
        ft.Row(
            [
                ft.ElevatedButton("Add Text", on_click=add_text),
                ft.ElevatedButton("Remove Text", on_click=remove_text),
            ],
            alignment=ft.MainAxisAlignment.CENTER,
        )
    )

ft.app(main)

 

Conclusion

The View in Flet is a flexible and essential component for creating dynamic interfaces. Its similarity to the Column control makes it intuitive to use, allowing developers to easily add and manipulate controls such as text, buttons, and other elements. Learning how to leverage the properties and methods of View is a crucial step in mastering development with Flet.