Home > database >  launch URL in Flet
launch URL in Flet

Time:12-04

I'm using Flet and I want for my app to launch a link when clicking on a button.

According to the docs, I can use launch_url method. But when I tried, I got the following error:

Exception in thread Thread-6 (open_repo):
Traceback (most recent call last):
  File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "d:\Iqmal\Documents\Python Projects\flet-hello\main.py", line 58, in open_repo
    ft.page.launch_url('https://github.com/iqfareez/flet-hello')
    ^^^^^^^^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'launch_url'

Code

import flet as ft


def main(page: ft.Page):

    page.padding = ft.Padding(20, 35, 20, 20)
    page.theme_mode = ft.ThemeMode.LIGHT

    appbar = ft.AppBar(
        title=ft.Text(value="Flutter using Flet"),
        bgcolor=ft.colors.BLUE,
        color=ft.colors.WHITE,
        actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])

    page.controls.append(appbar)

    page.update()


def open_repo(e):
    ft.page.launch_url('https://github.com/iqfareez/flet-hello')


ft.app(target=main, assets_dir='assets')

CodePudding user response:

To fix the error you're getting, you need to import the page module from the flet library and then create an instance of the page class. Then, you can call the launch_url method on that instance to open a URL in the default web browser.

Here's how you might update your code to do that:

import flet as ft

Import the page module from the flet library

from flet import page

def main(page: ft.Page):

# Create a new page object
my_page = page.Page()

# Set the padding and theme mode for the page
my_page.padding = ft.Padding(20, 35, 20, 20)
my_page.theme_mode = ft.ThemeMode.LIGHT

# Create an app bar and add it to the page
appbar = ft.AppBar(
    title=ft.Text(value="Flutter using Flet"),
    bgcolor=ft.colors.BLUE,
    color=ft.colors.WHITE,
    actions=[ft.IconButton(icon=ft.icons.CODE, on_click=open_repo)])

my_page.controls.append(appbar)

# Update the page to display the changes
my_page.update()

def open_repo(e): # Use the launch_url method to open a URL in the default web browser my_page.launch_url('https://github.com/iqfareez/flet-hello')

Run the app using the main function as the target

ft.app(target=main, assets_dir='assets')

CodePudding user response:

From what I'm seeing here and the errors you're getting it's just possible you might have a problem with the installation of Flet. Try installing running in a virtual environment and see if it changes.

Good Luck

  • Related