Skip to content

Markdown

Examples#

Live example

Basic Example#

import flet as ft

sample = """
# Markdown Example
Markdown allows you to easily include formatted text, images, and even formatted Dart code in your app.

## Titles

Setext-style

This is an H1
=============

This is an H2
-------------

Atx-style

# This is an H1

## This is an H2

###### This is an H6

Select the valid headers:

- [x] `# hello`
- [ ] `#hello`

## Links

[inline-style](https://www.google.com)

## Images

![Image from Flet assets](/icons/icon-192.png)

![Test image](https://picsum.photos/200/300)

## Tables

|Syntax                                 |Result                               |
|---------------------------------------|-------------------------------------|
|`*italic 1*`                           |*italic 1*                           |
|`_italic 2_`                           | _italic 2_                          |
|`**bold 1**`                           |**bold 1**                           |
|`__bold 2__`                           |__bold 2__                           |
|`This is a ~~strikethrough~~`          |This is a ~~strikethrough~~          |
|`***italic bold 1***`                  |***italic bold 1***                  |
|`___italic bold 2___`                  |___italic bold 2___                  |
|`***~~italic bold strikethrough 1~~***`|***~~italic bold strikethrough 1~~***|
|`~~***italic bold strikethrough 2***~~`|~~***italic bold strikethrough 2***~~|

## Styling

Style text as _italic_, __bold__, ~~strikethrough~~, or `inline code`.

- Use bulleted lists
- To better clarify
- Your points

## Code blocks

Formatted Dart code looks really pretty too:
void main() { runApp(MaterialApp( home: Scaffold( body: ft.Markdown(data: markdownData), ), )); }
"""


def main(page: ft.Page):
    page.scroll = ft.ScrollMode.AUTO

    def handle_link_tap(e: ft.Event[ft.Markdown]):
        page.launch_url(e.data)

    page.add(
        ft.Markdown(
            value=sample,
            selectable=True,
            extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
            on_tap_link=handle_link_tap,
        )
    )


ft.run(main)

basic

Code syntax highlight#

import flet as ft

sample = """
# Flet

<img src="https://raw.githubusercontent.com/flet-dev/flet/flet-widget/media/logo/flet-logo.svg" width="50%"/>

Flet is a framework for adding server-driven UI (SDUI) experiences to existing Flutter apps or building standalone web, mobile and desktop apps with Flutter UI.

Add an interactive `FletApp` widget to your Flutter app whose content is controlled by a remote Python script.
It is an ideal solution for building non-core or frequently changing functionality such as product catalog, feedback form, in-app survey or support chat. Flet enables your team to ship new features faster by reducing the number of App Store validation cycles. Just re-deploy a web app hosting a Python script and your users will get an instant update!

On the server side Flet provides an easy to learn programming model that enables Python developers without prior Flutter (or even front-end) experience to participate in development of your larger Flutter app or build their own apps with Flutter UI from scratch.

## Getting started with Flet

### Install `flet` Python module

Flet requires Python 3.7 or above. To start with Flet, you need to install flet module first:
pip install flet
### Create Python program

Create a new Python program using Flet which will be driving the content of `FletApp` widget.

Let's do a simple `counter.py` app similar to a Flutter new project template:

```python
import flet
from flet import IconButton, Page, Row, TextField, icons

def main(page: Page):
    page.title = "Flet counter example"
    page.vertical_alignment = "center"

    txt_number = TextField(value="0", text_align="right", width=100)

    def minus_click(e):
        txt_number.value = int(txt_number.value) - 1
        page.update()

    def plus_click(e):
        txt_number.value = int(txt_number.value) + 1
        page.update()

    page.add(
        Row(
            [
                IconButton(icons.REMOVE, on_click=minus_click),
                txt_number,
                IconButton(icons.ADD, on_click=plus_click),
            ],
            alignment="center",
        )
    )

flet.app(main, port=8550)

Run the app:

python counter.py

You should see the app running in a native OS window.

There is a web server (Fletd) running in the background on a fixed port 8550. Fletd web server is a "bridge" between Python and Flutter.

FletApp widget in your Flutter application will be communicating with Fletd web server via WebSockets to receive UI updates and send user-generated UI events.

For production use Python app along with Fletd could be deployed to a public web host and be accessible via HTTPS with domain name.

Add Flet widget to a Flutter app#

Create a new or open existing Flutter project.

Install Flutter flet package:

flutter pub add flet

For a new project replace main.dart with the following:

import 'package:flet/flet.dart';
import 'package:flutter/material.dart';

void main() async {
  await setupDesktop();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flet Flutter Demo',
      home: FletApp(pageUrl: "http://localhost:8550"),
    );
  }
}

In the app above FletApp widget is hosted inside MaterialApp widget.

If Flet app must be able to handle page route change events (web browser URL changes, mobile app deep linking) it must be the top most widget as it contains its own MaterialApp widget handling route changes:

import 'package:flet/flet.dart';
import 'package:flutter/material.dart';

void main() async {
  await setupDesktop();
  runApp(const FletApp(pageUrl: "http://localhost:8550"));
}

Run the program and see Flet app running inside a Flutter app.

When adding FletApp widget to the existing desktop Flutter app make sure setupDesktop() is called before runApp() to initialize Flet's built-in window manager.

Flet learning resources#

Flet community#

FAQ#

Coming soon.

Adding custom Flutter widgets#

Coming soon. """

def main(page: ft.Page): page.scroll = ft.ScrollMode.AUTO

page.fonts = {
    "Roboto Mono": "RobotoMono-VariableFont_wght.ttf",
}

page.add(
    ft.Markdown(
        value=sample,
        selectable=True,
        extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
        code_theme=ft.MarkdownCodeTheme.ATOM_ONE_DARK,
        code_style_sheet=ft.MarkdownStyleSheet(
            code_text_style=ft.TextStyle(font_family="Roboto Mono")
        ),
        on_tap_link=lambda e: page.launch_url(e.data),
    )
)

ft.run(main)

![code-syntax-highlight](https://raw.githubusercontent.com/flet-dev/flet/main/sdk/python/examples/controls/markdown/media/code-syntax-highlight.png){width="80%"}
/// caption
///

### Custom text theme

```python
import flet as ft


def main(page: ft.Page):
    page.theme_mode = ft.ThemeMode.DARK

    def change_theme_mode(e: ft.Event[ft.Switch]):
        if page.theme_mode == ft.ThemeMode.DARK:
            page.theme_mode = ft.ThemeMode.LIGHT
            switch.thumb_icon = ft.Icons.LIGHT_MODE
        else:
            switch.thumb_icon = ft.Icons.DARK_MODE
            page.theme_mode = ft.ThemeMode.DARK
        page.update()

    switch = ft.Switch(thumb_icon=ft.Icons.DARK_MODE, on_change=change_theme_mode)

    page.add(
        ft.Row(
            alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
            controls=[
                ft.Container(
                    content=ft.Markdown("I can read this!"),
                    bgcolor="#550000",
                    padding=20,
                    theme=ft.Theme(
                        text_theme=ft.TextTheme(
                            body_medium=ft.TextStyle(color=ft.Colors.WHITE),
                            body_large=ft.TextStyle(color=ft.Colors.WHITE),
                            body_small=ft.TextStyle(color=ft.Colors.WHITE),
                        )
                    ),
                ),
                ft.Container(
                    content=switch,
                    padding=ft.Padding.only(bottom=50),
                    alignment=ft.Alignment.TOP_RIGHT,
                ),
            ],
        )
    )


ft.run(main)

Markdown #

Bases: ConstrainedControl

Renders text in markdown format.

animate_offset #

animate_offset: AnimationValue | None = None

Enables implicit animation of the offset property.

More information here.

animate_opacity #

animate_opacity: AnimationValue | None = None

Enables implicit animation of the opacity property.

More information here.

animate_position #

animate_position: AnimationValue | None = None

Enables implicit animation of the positioning properties (left, right, top and bottom).

More information here.

animate_rotation #

animate_rotation: AnimationValue | None = None

Enables implicit animation of the rotate property.

More information here.

animate_scale #

animate_scale: AnimationValue | None = None

Enables implicit animation of the scale property.

More information here.

animate_size #

animate_size: AnimationValue | None = None

TBD

aspect_ratio #

aspect_ratio: Number | None = None

TBD

auto_follow_links: bool = False

Automatically open URLs in the document.

If registered, on_tap_link event is fired after that.

auto_follow_links_target: UrlTarget | None = None

Where to open URL in the web mode.

badge #

badge: BadgeValue | None = None

A badge to show on top of this control.

bottom #

bottom: Number | None = None

The distance that the child's bottom edge is inset from the bottom of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

code_style_sheet #

code_style_sheet: MarkdownStyleSheet | None = None

The styles to use when displaying the code blocks.

code_theme #

code_theme: (
    MarkdownCodeTheme | MarkdownCustomCodeTheme | None
) = None

A syntax highlighting theme for code blocks.

Defaults to MarkdownCodeTheme.GITHUB.

col #

col: ResponsiveNumber = 12

If a parent of this control is a ResponsiveRow, this property is used to determine how many virtual columns of a screen this control will span.

Can be a number or a dictionary configured to have a different value for specific breakpoints, for example col={"sm": 6}.

This control spans the 12 virtual columns by default.

Dimensions
Breakpoint Dimension
xs <576px
sm ≥576px
md ≥768px
lg ≥992px
xl ≥1200px
xxl ≥1400px

data #

data: Any = skip_field()

Arbitrary data of any type.

disabled #

disabled: bool = False

Every control has disabled property which is False by default - control and all its children are enabled.

Note

The value of this property will be propagated down to all children controls recursively.

Example

For example, if you have a form with multiple entry controls you can disable them all together by disabling container:

ft.Column(
    disabled = True,
    controls=[
        ft.TextField(),
        ft.TextField()
    ]
)

expand #

expand: bool | int | None = None

Specifies whether/how this control should expand to fill available space in its parent layout.

More information here.

Note

Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.

expand_loose #

expand_loose: bool = False

Allows the control to expand along the main axis if space is available, but does not require it to fill all available space.

More information here.

Note

If expand_loose is True, it will have effect only if:

  • expand is not None and
  • the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.

extension_set #

extension_set: MarkdownExtensionSet = NONE

The extensions to use when rendering the markdown content.

fit_content #

fit_content: bool = True

Whether to allow the widget to fit the child content.

height #

height: Number | None = None

Imposed Control height in virtual pixels.

image_error_content #

image_error_content: Control | None = None

The control to display when an image fails to load.

key #

key: (
    str | int | float | bool | ValueKey | ScrollKey | None
) = None

left #

left: Number | None = None

The distance that the child's left edge is inset from the left of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

md_style_sheet #

md_style_sheet: MarkdownStyleSheet | None = None

The styles to use when displaying the markdown.

offset #

offset: OffsetValue | None = None

Applies a translation transformation before painting the control.

The translation is expressed as an Offset scaled to the control's size. So, Offset(x=0.25, y=0), for example, will result in a horizontal translation of one quarter the width of this control.

Example

The following example displays container at 0, 0 top left corner of a stack as transform applies -1 * 100, -1 * 100 (offset * control's size) horizontal and vertical translations to the control:

import flet as ft

def main(page: ft.Page):
    page.add(
        ft.Stack(
            width=1000,
            height=1000,
            controls=[
                ft.Container(
                    bgcolor="red",
                    width=100,
                    height=100,
                    left=100,
                    top=100,
                    offset=ft.Offset(-1, -1),
                )
            ],
        )
    )

ft.run(main)

on_animation_end #

on_animation_end: (
    ControlEventHandler[ConstrainedControl] | None
) = None

Called when animation completes.

Can be used to chain multiple animations.

The data property of the event handler argument contains the name of the animation.

More information here.

on_selection_change #

on_selection_change: (
    EventHandler[TextSelectionChangeEvent[Markdown]] | None
) = None

Called when the text selection changes.

on_tap_link: ControlEventHandler[Markdown] | None = None

Called when a link within Markdown document is clicked/tapped.

The data property of the event handler argument contains the clickedURL.

Example: https://github.com/flet-dev/examples/blob/main/python/controls/information-displays/markdown/markdown-event-example.py

on_tap_text #

on_tap_text: ControlEventHandler[Markdown] | None = None

Called when some text is clicked/tapped.

opacity #

opacity: Number = 1.0

Defines the transparency of the control.

Value ranges from 0.0 (completely transparent) to 1.0 (completely opaque without any transparency).

page #

page: Page | PageView | None

The page (of type Page or PageView) to which this control belongs to.

parent #

parent: BaseControl | None

The direct ancestor(parent) of this control.

It defaults to None and will only have a value when this control is mounted (added to the page tree).

The Page control (which is the root of the tree) is an exception - it always has parent=None.

right #

right: Number | None = None

The distance that the child's right edge is inset from the right of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

rotate #

rotate: RotateValue | None = None

Transforms this control using a rotation around its center.

The value of rotate property could be one of the following types:

  • number - a rotation in clockwise radians. Full circle 360° is math.pi * 2 radians, 90° is pi / 2, 45° is pi / 4, etc.
  • Rotate - allows to specify rotation angle as well as alignment - the location of rotation center.
Example

For example:

ft.Image(
    src="https://picsum.photos/100/100",
    width=100,
    height=100,
    border_radius=5,
    rotate=Rotate(angle=0.25 * pi, alignment=ft.Alignment.CENTER_LEFT)
)

rtl #

rtl: bool = False

Whether the text direction of the control should be right-to-left (RTL).

scale #

scale: ScaleValue | None = None

Scales this control along the 2D plane. Default scale factor is 1.0, meaning no-scale.

Setting this property to 0.5, for example, makes this control twice smaller, while 2.0 makes it twice larger.

Different scale multipliers can be specified for x and y axis, by setting Control.scale property to an instance of Scale class. Either scale or scale_x and scale_y could be specified, but not all of them.

Example
ft.Image(
    src="https://picsum.photos/100/100",
    width=100,
    height=100,
    border_radius=5,
    scale=ft.Scale(scale_x=2, scale_y=0.5)
)

selectable #

selectable: bool = False

Whether rendered text is selectable or not.

shrink_wrap #

shrink_wrap: bool = True

Whether the extent of the scroll view in the scroll direction should be determined by the contents being viewed.

soft_line_break #

soft_line_break: bool = False

The soft line break is used to identify the spaces at the end of a line of text and the leading spaces in the immediately following the line of text.

tooltip #

tooltip: TooltipValue | None = None

The tooltip ot show when this control is hovered over.

top #

top: Number | None = None

The distance that the child's top edge is inset from the top of the stack.

Note

Effective only if this control is a descendant of one of the following: Stack control, Page.overlay list.

value #

value: str = ''

Markdown content to render.

visible #

visible: bool = True

Every control has visible property which is True by default - control is rendered on the page. Setting visible to False completely prevents control (and all its children if any) from rendering on a page canvas. Hidden controls cannot be focused or selected with a keyboard or mouse and they do not emit any events.

width #

width: Number | None = None

Imposed Control width in virtual pixels.

before_event #

before_event(e: ControlEvent)

before_update #

before_update()

clean #

clean() -> None

did_mount #

did_mount()

init #

init()

is_isolated #

is_isolated()

update #

update() -> None

will_unmount #

will_unmount()