Search code examples
pythonflutterflet

launch URL in Flet


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')

Solution

  • I 'solved' this issue by moving the open_repo() function inside the main() function block. Now, the link can be opened on a browser when clicked. Example:

    def main(page: ft.Page):
    
        def open_repo(e):
            page.launch_url('https://github.com/iqfareez/flet-hello')
    
        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)])
    
        # code truncated for clarity
    

    Full code here.