Sitemap

Python UI Reusability using Flet — With Code

6 min readDec 8, 2022
Press enter or click to view image in full size
Python UI reusability — Flet

Re-usability is a key when it comes to UI design. You create a widget once, and it should be at your disposal at anytime through out your code with the least code possible.

Take the example of a navigation bar at the top of your App or Webpage. This bar requirement maybe to be displayed on every page or every view of your app. If usability is not taken into account, your code will turn into a giant spaghetti, because you will be reimplementing unnecessary details for this navigation-bar in every view or page of your app.

The essence of reusability is to utilize Object Oriented Programming Techniques. by the least, you need to treat every widget you have as a separate class.

Utilizing only functions to create and pass around widgets is what will be harming your reusability on the long run.

Take for example a Tasking App where you can write your daily tasks one by one through a text field, and then the app will generate that task as a check box with the text your typed next to it:

Press enter or click to view image in full size
Figure1: Tasking App-Adding Task Work-Flow
Press enter or click to view image in full size
Figure2: Tasking App- Editing a Task Work-Flow
Press enter or click to view image in full size
Figure3: Tasking App- Deleting Task Work-Flow

This is a very simple example on Usability Our elements are:

  1. Text Field to type your task in
  2. Add Button which will trigger a widget to be generated containing your Task Text, and a Check box, Delete and Edit Buttons
  3. Generated Task

View Modes:

We have two view modes for every created task:

  1. Display Mode: This is the default mode we see in Figure 1. It simply shows our task , with a Delete and Edit Buttons next to it
  2. Edit Mode : This is the mode we see in Figure 2, where it will pop up when we click on the Edit Button of a task.
    This mode shows a TextField where the user can edit the previously added task.
    There is also a Save Button next to it to save the edited text after

Only one of the modes can be active at a time.

Code Design:

Get The Python Dude’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s consider the User Text Field where we type in our task as a separate widget, and create a class for it. It will also hold any created Tasks.

A second class will be created which will be used to generate Task Text with its buttons (Delete and Edit).
This second class should also support both View Modes.

Flutter for Python — Flet:

We will be using the amazing Flet library to demonstrate this concept.
Flet is a python library a based on the Famous UI Tool Kit from Google (uses Dart Programming language). It used to create cool Cross-Platform UI seamlessly.

If you are new to Flutter, check out this 30-min Video to get you started.

Let’s write some code!

Let’s create the logic to Add a new Task by typing to the Text Field.
We will create a class called TasksApp which will handle adding a new Task to the view, and will serve as the UserTextField (Text Field and Add Button) Widget.

import flet as ft

#Create a TasksApp Class inheriting from ft.UserControl
class TasksApp(ft.UserControl):

#Build must be implemented which will return the UserTextField along with
#The Add Button
def build(self):

#Column that will contain every created Task
self.tasks = ft.Column()

#Text Field to type our task in
self.textField = ft.TextField(width=350)

#Define Add Button with an Icon next to it
#This will trigger addClicked method when clicked
self.addBtn = ft.FloatingActionButton(icon= ft.icons.ADD,
on_click=self.addClicked)

#Create a row containing your TextField and the button you
#Created Above
taskRow=ft.Column(controls=[
ft.Row(controls=[self.textField, self.addBtn, ]),self.tasks], )
return taskRow

#Function to be triggered when clicking Add Button
def addClicked(self,e):
#Create a task Object (we will program it later below)
#It receives the text the user typed, and a we pass
#taskDelete Methode to it. Which will be used as a reference
#To delete the task
task=Task(self.textField.value, self.taskDelete)
self.tasks.controls.append(task)

#After typing in a task, reset the textField to be ready for
#a new task to be written
self.textField.value=""

#Call update method from the inherited UserControl to
#Update the view
self.update()
#Method to be passed to Task Object which will remove
#The task from the View when pressing Delete
def taskDelete(self,task):
self.tasks.controls.remove(task)
self.update()

Next we will create the Task Class which will handle the New Task created. Including handling both View Modes.

Since a new task should be created with Every Add Click, we are treating that task a seperate widget. Which makes sense.
This widget Class is like a living creature. It has methods to Edit, Save, and Delete. This will make our life easier since every task will maintain its state and will take care of it self. All we need to do is trigger an action using a Button.
It will also take care of the View Mode. By hiding or showing a certain mode depending on the button pressed.

e.g:
If Edit is pressed, Edit mode should be visible.
Otherwise, display mode should be visible.

Note that we are creating both modes in the same class and our job is to only write the logic to when to show each mode.

class Task(ft.UserControl):

#Call super since we are passing extra parameters to the
#Inherited UserControl
#Handle TaskName(The text we typed)
#And taskDelete (The task delete function reference we passed above)
def __init__(self, taskName,taskDelete):
super().__init__()
self.taskName=taskName
self.taskDelete= taskDelete

#Implement the Compulsery Build Method
#Which will return a Task Widget (The text your wrote with edit and
#Delete Buttons)
def build(self):
#Add a check box with the text next to it(the text is taskname)
#Which is the text you typed in
#Makse sure vlaue is False. So that the box is unchecked
self.displayTask =ft.Checkbox(value=False, label= self.taskName)
self.editName = ft.TextField()

#Those are the modes, editView and displayView
#It consist of a Row, containing the text you have writted
#And another row containing the Edit and Delete buttons

#This display view is initially visible
#Note that The first button will trigger editClick Method
#And second button will trigger deleteClick Method
self.displayView= ft.Row(alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
controls=[self.displayTask,
ft.Row(controls=[ft.IconButton(ft.icons.CREATE_OUTLINED,
on_click=self.editClick),
ft.IconButton(ft.icons.DELETE_OUTLINED,
on_click=self.deleteClick
)])])
#Edit view is initially invisible.
#Notce that it consist of a row containing, the text you have written
#and a save button
#Save button will trigger saveClickMethod
self.editView = ft.Row(visible=False,
controls=[self.editName,
ft.IconButton(icon=ft.icons.DONE_OUTLINED,
on_click=self.saveClick
)])
#We are returning both views as a column
#Even though only one of the views is visible at a time
return ft.Column(controls=[self.displayView, self.editView])

#This method is triggered when edit button is pressed
#It reads whatever text the Task contained
#And move it to the edit view (You don't want the Task text to be
#Empty when clicking on edit right)
#Next it sets the editView to visible and displayView to invisible
#And we update the view
def editClick(self,e):
self.editName.value=self.displayTask.label
self.displayView.visible=False
self.editView.visible=True
self.update()

#This is triggerd when we click on the save button in editMode
# we set back displayView to visible and editView to invisible.
#Beause well, we are done with editing
def saveClick(self,e):
self.displayTask.label=self.editName.value
self.displayView.visible=True
self.editView.visible=False
self.update()

#This is triggered when we click on delete in displayView
#This method will trigger the reference we passed through TasksApp
#And will remove the Task from the list
def deleteClick(self,e):
self.taskDelete(self)

Now we will simply wirte our main and run the program.

def main(page: ft.page):
page.window_width=500
page.window_height=700
page.bgcolor ="WHITE"
app = TasksApp()

page.add(app )

ft.app(target=main)

And this is the final look ( We can still work on making it look nicer)

Tasking App By PythonDude

And that’s it. This how we can easily create a re-usable UI.

The example was for a simple app, but those work-flow concepts can be generalized to any App you are creating.

If this was to be created using Pure Functions, it would’ve been a mess. Handling Edit, delete and Save can be a nightmare because we would need to pass references for every created task all over the place. Which gets ugly pretty quickly.

--

--

The Python Dude
The Python Dude

Data Analysis | Digital Twin| Embedded Software Developer | Content Creator