The Wayback Machine - https://web.archive.org/web/20241006001202/https://www.geeksforgeeks.org/building-flutter-apps-in-python/
Open In App

Building Flutter Apps in Python

Last Updated : 05 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, Here we will use Flutter apps in Python, for this library Flet will help to Build the Application.

What is Flet?

Flet is a Python Library using which developers can build real-time web apps, Mobile Apps, and Desktop apps without directly using Flutter. As to building apps using Flutter, developers need to learn Dart language but using Flet module just using Python codes we can build Apps that will work similarly to apps built in Flutter.

Required Modules:

For this tutorial, we will be using Flet module only. To install it using pip run the following command in the terminal.

pip install flet

We would recommend the user create and use a Virtual Environment for this Tutorial, and install the flet package there.

 

Importing the module:

Python3




import flet as flt
  
def myapp(page: flt.Page):
    pass
  
  
flt.app(target=myapp)


Output:

 

A blank page with default theme opens with this infinitely loading animation as we have nothing in the function till now.

The function’s name can be anything while calling the app method we just have to pass the Target function’s name to include all the features we have mentioned inside of that function is visible in our app.

Running the Program

We can use the traditional method of writing python <file_name.py> to run flet files, but the problem we will face that if we make any change we need to stop the code execution and rerun it, but if we use the flet in front of the filename instead of python, all the changes will be visible instantly.

flet <filename.py>

Remember if the file is not present in the directory we user is currently in, then in place of filename.py user need to provide the full path + filename,py

Changing the Theme of the App

We can also change the theme of the app, either Light or Dark. By default, flet will make the app in the default mode of our device. If our device is in Light Mode it will create the app in Light Mode, if it is in Dark Mode then the app will also be in dark mode.

Python3




import flet as flt
  
def myapp(page: flt.Page):
    page.theme_mode = flt.ThemeMode.DARK # change DARK to LIGHT to convert it to light mode
    page.window_height = 400
    page.window_width = 500
  
    page.title = 'GeeksApp using Flet'
  
    page.update()
  
  
flt.app(target=myapp)


Output:

 

Adding some text into our App

Now we will add some text into our App using the TextField and add method. add method is used to add the widgets or anything we are adding into our app and always keep it updated with our code, if we use add method we can omit the update method we were using previously. But the things we are not adding using the add method like the page title will not be shown as we are not updating the page, so if we only use widgets and we add all of them then we can remove the update method, otherwise we need to keep it. It will not throw any error or anything if we keep both update and add.

Python3




import flet as flt
  
def myapp(page: flt.Page):
    page.theme_mode = flt.ThemeMode.LIGHT
    page.window_height = 400
    page.window_width = 500
  
    text = flt.TextField(
        label="Introductory Text",
        value="This App is made using Flet"
    )
  
    page.add(text)
  
    page.title = 'GeeksApp using Flet'
  
    page.update()
  
  
flt.app(target=myapp)


Output:

 

The TextField method by default comes with a border, we have added a label and its value has been used as Introductory Text which will always be shown in the top left corner of TextField, This App is made using Flet is the value stored in the Textfield. If we want to remove the border we need to add a simple keyword argument in the TextField method.

Python3




text = flt.TextField(
        label="Introductory Text",
        value="This App is made using Flet",
        border = flt.InputBorder.NONE
        )


Output:

 

by default, the value of the border is OUTLINE, if we don’t want to see any border, we will change it to NONE, if we want to only get an underline we will use UNDERLINE.

Python3




text = flt.TextField(
        label="Introductory Text",
        value="This App is made using Flet",
        border = flt.InputBorder.UNDERLINE
        )


Output:

 

TextField can also consist of Numbers, but we have to pass them as Strings.

 We can also add some simple texts by using the Text method inside of add method:

Python3




import flet as flt
  
def myapp(page: flt.Page):
    page.theme_mode = flt.ThemeMode.LIGHT
    page.window_height = 400
    page.window_width = 500
  
    page.add(
        flt.Text("Hello Geeks",
        size = 40,
        color = flt.colors.GREEN,
        bgcolor = flt.colors.YELLOW_300,
        weight=flt.FontWeight.BOLD,
    ))
  
    page.title = 'GeeksApp using Flet'
  
    page.update()
  
  
flt.app(target=myapp)


Output:

 

the text’s size is 40, the color is normally green, the background color is Yellow_300, the greater the number after a color, deeper it looks, and the weight of the font is Bold. 

Simple Calculator using Flet

We will now create a very simple calculator using flet module and whatever we have learned till now with some extra functionalities.

Explanation

  • Firstly imported all the modules and functions we use. All of them belong to flet. No other module will be used here.
  • Then created the main Calculator class which we will use to design the structure, color, padding, width and everything we can see.
  • Two types of buttons are being used here FilledButton and Elevated Button.
    • FilledButton are certain buttons which mostly used to describe important or final actions or end of flow. These kind of buttons have been used here for all the numbers.
    • ElevatedButton – as the name suggests , these are a type of button which remains ‘elevated’ before pressing and if we disable it then it becomes unresponsive (Like those buttons which we can’t press twice, it becomes unresponsive). To express the operators this type has been used. As disabling has not been enabled so it will not be disabled if pressed more than once.
  • Inside both type of Buttons a method on_button_clicked has been passed which will tell what to do if we press certain buttons. Elevated buttons have certain background color and font color but FilledButton doesn’t have them. Also in both case the text parameter holds what will be visible in our calculator and data means what will be put after pressing the button.
  • Then inside the on_button_clicked method all the operations for different operators are defined. Like for addition how the operation will be carried out, same for other available operations.
  • format_number method is used to either print the result in int or as it is (maybe in float with some amount of numbers after decimal place).
  • Then the calculate_value method is used to calculate the values internally for each different available operators. This function is above used inside the on_button_clicked method inside which we have defined what will happen if we press certain buttons.
  • the reset method is of two use. 
    • If the user presses AC on the calculator it will reset everything and display 0.
    • If the user presses ‘=’ then it will erase all other numbers and display only the updated result.
  • myCal function is out of the class CalculatorApp, inside which we will make an instance of that class and modify the width and height of the app we want to display, Note : This will not update the width of the calculator, this will update the width and height of the external window which will be shown after running the code. This is solely created as to run this app we need to use the app method of flet module and pass a function to it.

Python3




import flet
from flet import (
    Column,
    Container,
    ElevatedButton,
    Page,
    Row,
    Text,
    UserControl,
    border_radius,
    colors,
    FilledButton
)
  
  
class CalculatorApp(UserControl):
    def build(self):
        self.reset()
        self.result = Text(value="0", color=colors.WHITE, size=22)
  
        # application's root control (i.e. "view") containing all other controls
        return Container(
            width=325,
            bgcolor=colors.BLUE_900,
            border_radius=border_radius.all(15),
            padding=20,
            content=Column(
                controls=[
                    Row(controls=[self.result], alignment="end"),
                    Row(
                        controls=[
                            ElevatedButton(
                                text="AC",
                                bgcolor=colors.YELLOW_400,
                                color=colors.BLACK,
                                on_click=self.on_button_clicked,
                                data="AC",
                            ),
                            ElevatedButton(
                                text="+/-",
                                bgcolor=colors.YELLOW_400,
                                color=colors.BLACK,
                                on_click=self.on_button_clicked,
                                data="+/-",
                            ),
                            ElevatedButton(
                                text="%",
                                bgcolor=colors.GREEN_900,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data="%",
                            ),
                            ElevatedButton(
                                text="/",
                                bgcolor=colors.GREEN_900,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data="/",
                            ),
                        ],
                    ),
                    Row(
                        controls=[
                            FilledButton(
                                text="7",
                                on_click=self.on_button_clicked,
                                data="7",
                            ),
                            FilledButton(
                                text="8",
                                on_click=self.on_button_clicked,
                                data="8",
                            ),
                            FilledButton(
                                text="9",
                                on_click=self.on_button_clicked,
                                data="9",
                            ),
                            ElevatedButton(
                                text="*",
                                bgcolor=colors.GREEN_900,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data="*",
                            ),
                        ]
                    ),
                    Row(
                        controls=[
                            FilledButton(
                                text="4",
                                on_click=self.on_button_clicked,
                                data="4",
                            ),
                            FilledButton(
                                text="5",
                                on_click=self.on_button_clicked,
                                data="5",
                            ),
                            FilledButton(
                                text="6",
                                on_click=self.on_button_clicked,
                                data="6",
                            ),
                            ElevatedButton(
                                text="-",
                                bgcolor=colors.GREEN_900,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data="-",
                            ),
                        ]
                    ),
                    Row(
                        controls=[
                            FilledButton(
                                text="1",
                                on_click=self.on_button_clicked,
                                data="1",
                            ),
                            FilledButton(
                                text="2",
                                on_click=self.on_button_clicked,
                                data="2",
                            ),
                            FilledButton(
                                text="3",
                                on_click=self.on_button_clicked,
                                data="3",
                            ),
                            ElevatedButton(
                                text="+",
                                on_click=self.on_button_clicked,
                                bgcolor=colors.GREEN_900,
                                color=colors.WHITE,
                                data="+",
                            ),
                        ]
                    ),
                    Row(
                        controls=[
                            FilledButton(
                                text="0",
                                on_click=self.on_button_clicked,
                                data="0",
                            ),
                            FilledButton(
                                text="00",
                                on_click=self.on_button_clicked,
                                data="00",
                            ),
                            ElevatedButton(
                                text=".",
                                bgcolor=colors.AMBER_600,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data=".",
                            ),
                            ElevatedButton(
                                text="=",
                                bgcolor=colors.ORANGE,
                                color=colors.WHITE,
                                on_click=self.on_button_clicked,
                                data="=",
                            ),
                        ]
                    ),
                ],
            ),
        )
  
    def on_button_clicked(self, e):
        data = e.control.data
        if self.result.value == "Error" or data == "AC":
            self.result.value = "0"
            self.reset()
  
        elif data in ("1", "2", "3", "4", "5", "6", "7", "8",
                      "9", "0", ".", "00"):
            if self.result.value == "0" or self.new_operand == True:
                self.result.value = data
                self.new_operand = False
            else:
                self.result.value = self.result.value + data
  
        elif data in ("+", "-", "*", "/"):
            self.result.value = self.calculate_value(
                self.operand1, float(self.result.value), self.operator
            )
            self.operator = data
            if self.result.value == "Error":
                self.operand1 = "0"
            else:
                self.operand1 = float(self.result.value)
            self.new_operand = True
  
        elif data in ("="):
            self.result.value = self.calculate_value(
                self.operand1, float(self.result.value), self.operator
            )
            self.reset()
  
        elif data in ("%"):
            self.result.value = float(self.result.value) / 100
            self.reset()
  
        elif data in ("+/-"):
            if float(self.result.value) > 0:
                self.result.value = "-" + str(self.result.value)
  
            elif float(self.result.value) < 0:
                self.result.value = str(
                    self.format_number(abs(float(self.result.value)))
                )
  
        self.update()
  
    def format_number(self, num):
        if num % 1 == 0:
            return int(num)
        else:
            return num
  
    def calculate_value(self, operand1, operand2, operator):
  
        if operator == "+":
            return self.format_number(operand1 + operand2)
  
        elif operator == "-":
            return self.format_number(operand1 - operand2)
  
        elif operator == "*":
            return self.format_number(operand1 * operand2)
  
        elif operator == "/":
            if operand2 == 0:
                return "Error"
            else:
                return self.format_number(operand1 / operand2)
  
    def reset(self):
        self.operator = "+"
        self.operand1 = 0
        self.new_operand = True
  
  
def myCal(page: flet.Page):
    page.title = "Basic Calculator using Flet"
  
    page.window_height = 375
    page.window_width = 350
  
    calculator = CalculatorApp()
  
    page.update()
  
    # adding application's root control to the page
    page.add(calculator)
  
  
flet.app(target=myCal)


Output:

 



Similar Reads

Building Calculator using PyQt5 in Python
In this article we will see how we can create a calculator using PyQt5,A calculator is something used for making mathematical calculations, in particular a small electronic device with a keyboard and a visual display. below is the how the calculator will looks like GUI implementation steps Create a label to show the numbers and the output and set i
5 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Building a basic HTTP Server from scratch in Python
In this article, we are going to learn how to set up a simple and local HTTP server using Python. An HTTP server can be very useful for testing Android, PC, or Web apps locally during development. It can also be used to share files between two devices connected over the same LAN or WLAN network. Installation: On the terminal run the following state
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Building CLI to check status of URL using Python
In this article, we will build a CLI(command-line interface) program to verify the status of a URL using Python. The python CLI takes one or more URLs as arguments and checks whether the URL is accessible (or)not. Stepwise ImplementationStep 1: Setting up files and Installing requirements First, create a directory named "urlcheck" and create a new
4 min read
Building WhatsApp bot on Python
A WhatsApp bot is application software that is able to carry on communication with humans in a spoken or written manner. And today we are going to learn how we can create a WhatsApp bot using python. First, let's see the requirements for building the WhatsApp bot using python language. System Requirements:A Twilio account and a smartphone with an a
6 min read
Building Space Invaders Using PyGame - Python
In this article, we're going to build a Space Bullet shooter game using PyGame in Python. The used file can be downloaded from here. Approach: Import the required module.Initialize the pygame.Create three functions:isCollision(): Which tells us whether the collision has occurred or not?game_over(): Which returns True or False on the basis of which
13 min read
Building A Weather CLI Using Python
Trying to know the weather is something that we all do, every day. But have you ever dreamed of making a tool on your own that can do the same? If yes, then this article is for you. In this article, we will look at a step-by-step guide on how to build a Weather CLI using OpenWeather API. What is OpenWeather API?OpenWeather API is a weather API prov
4 min read
Building a terminal based online dictionary with Python and bash
I was watching a movie yesterday and I didn’t understand some of the words used. So what I did was, each time I didn’t understand any word, I’d fire up my browser and type in ‘define [word]’ and google would turn me up with the meaning of the word. But it’s annoying to open the browser every time (Blame me for that ;P). What do we geeks users love
4 min read
Building a Background PDF Generation App Using Python Celery and Template Data
In today's digital age, businesses often require the generation of PDF files with dynamic data for various purposes such as reports, invoices, or certificates. However, generating these PDF files synchronously within a web application can lead to performance issues and user experience degradation. To solve this, we can create a background app that
3 min read
Building Powerful Telegram Bots with Telethon in Python
Creating a Telegram bot can significantly enhance how you interact with users, automate tasks, and provide information quickly. Here, we'll use the Telethon library in Python to build a powerful Telegram bot. Creating Telegram Bot in PythonPrerequisites Telegram Account: We need a Telegram account to create and manage our bot.Telethon Library: We'l
4 min read
How to Deploy Python WSGI Apps Using Gunicorn HTTP Server Behind Nginx
This article describes how to deploy a Python WSGI application using Gunicorn and Nginx. Before proceeding with the tutorial, it's a good idea to first familiarize yourself with the terms WSGI, Gunicorn, and Nginx. Web Server Gateway Interface or WSGI is a specification that describes how a web server (in this case Nginx) interacts with a Python we
5 min read
Tableau - Building up a storyline
Visualisations are a part of business analysis. But it is also very important to communicate your findings effectively. Tableau 10 includes stories, which were first introduced in an update to version 8. Using stories, you create a sequence of story points consisting of worksheets in your workbook. You can use them to build a persuasive narrative a
2 min read
Building Blog CMS (Content Management System) with Django
Django is a python based web application framework that is helpful for building a variety of web applications. Django also includes an extensible Django-Admin interface, Default SQLIte3 database, which is also extensible to PostgreSQL, MySQL databases, and a few other components to build efficient web apps. Install and Setup Django Create a directo
10 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
Building a row from a dictionary in PySpark
In this article, we will discuss how to build a row from the dictionary in PySpark For doing this, we will pass the dictionary to the Row() method. Syntax: Syntax: Row(dict) Example 1: Build a row with key-value pair (Dictionary) as arguments. Here, we are going to pass the Row with Dictionary Syntax: Row({'Key':"value", 'Key':"value",'Key':"value"
1 min read
Building Recommendation Engines using Pandas
In this article, we learn how to build a basic recommendation engine from scratch using Pandas. Building Movie Recommendation Engines using Pandas A Recommendation Engine or Recommender Systems or Recommender Systems is a system that predicts or filters preferences according to each user's likings. Recommender systems supervise delivering an index
7 min read
Imputing Missing Values Before Building an Estimator in Scikit Learn
The missing values in a dataset can cause problems during the building of an estimator. Scikit Learn provides different ways to handle missing data, which include imputing missing values. Imputing involves filling in missing data with estimated values that are based on other available data in the dataset. Related topic of concepts:Missing Data: Mis
3 min read
Building RESTful APIs with FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. There is Another famous framework for doing the same is Flask, which is also Python-based. In this article, we will focus on creating a RESTful API using FastAPI. In this article, we will learn how to create a basic ToDo List API using FastAPI. FastAPI is a
5 min read
Building Mock APIs with Swagger
This step-by-step tutorial for constructing a mock API in Python using Swagger. In this article, we'll step through the full process, from defining our API with Swagger to developing and testing a mock server. Whether you're an experienced developer or just starting started, this article will show you how to construct Mock APIs with Swagger. The pr
8 min read
Building Web App with Django and FastAPI
Django is a powerful and popular web framework for building robust web applications with Python. It comes with a lot of built-in features, including an ORM, an authentication system, and a powerful admin interface. However, there are scenarios where you might want to integrate Django with FastAPI, a modern, fast (high-performance), web framework fo
4 min read
Building APIs using FastAPI with Django
Combining FastAPI and Django can leverage the strengths of both frameworks: FastAPI's high performance for building APIs and Django's powerful ORM and admin interface. In this guide, we'll outline how to integrate FastAPI into a Django project to build high-performance APIs. In this article, we will combine the strengths of both Django and FastAPI
3 min read
Building an Issue Tracker with Django
In this article, we will guide you through creating an Issue Tracker using Django. A Django issue tracker is a web-based application designed to help software development teams manage and track bugs, tasks, and feature requests efficiently. Leveraging Django's powerful framework, this project provides a structured approach to issue management throu
6 min read
Building QR Code Generator Application using PyQt5
In this article, we will see how we can make a QR code generator application using PyQt5. A QR code is a type of matrix barcode first designed in 1994 for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. Below is how the application will look like Requi
4 min read
Django - Creating Apps | Set - 1
Prerequisites: Django – Dealing with warnings Why do we need apps? In Django Set 2 (Creating a Project), we saw how we can display text in our browser using Django but that is not the best and pythonic way. Django recommends using the project-app relationship to build Django projects. Any website contains different sections. For example, Geeksforge
1 min read
Django - Creating apps | Set - 2
In the previous article, we discussed why apps are important in Django project management? What are the benefits of using Django apps? In this article, we will discuss what are we going to build and how do apps play a vital role in Django projects? Project outline - We will build a localhost e-commerce mobile phone website which can show us details
2 min read
Configuring Django Apps for Heroku
In this article, we will learn how to configure a Django app for Heroku step-by-step. Heroku is a cloud-based application deployment and management service which supports several programming languages such as Ruby, Java, Node.js, Scala, Clojure, Python, PHP, and Go. It requires a Procfile, this file is used to declare your entry points and applicat
2 min read
Making apps with Pygame
In this article, we will see how we can make a simple app with Pygame. Pygame is a library for python that helps us to build multimedia applications (Apps) and games. This library works as a wrapper for Simple DirectMedia Layer (SDL). ApproachCreate the app classAdd text class.Add Screen classSet Different windows.What are Classes? A class is a tem
8 min read
How to Add Graphs to Flask apps
In this article, we will use the Flask framework to create our web application in Python. The Bokeh library will be used to create interactive bar graphs and we will visualize this graph through a simple frontend HTML page. For this, we will first write the endpoints in Flask which will help us to create Bokeh charts, and then we will create HTML t
5 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read