Skip to content

DropdownM2 继承自: FormFieldControl, LayoutControl, Control, BaseControl

A dropdown lets the user select from a number of items. The dropdown shows the currently selected item as well as an arrow that opens a menu for selecting another item.

Example:

python
ft.DropdownM2(
    width=220,
    value="Alice",
    options=[
        ft.dropdownm2.Option(key="Alice", text="Alice"),
        ft.dropdownm2.Option(key="Bob", text="Bob"),
    ],
)

属性 ​

名称类型默认值说明
valueOptional[str]Nonekey value of the selected option.
optionsOptional[list[Option]]NoneA list of Option controls representing items in this dropdown.
alignmentOptional[Alignment]NoneDefines how the hint or the selected item is positioned within this dropdown.
autofocusboolFalseTrue if the control will be selected as the initial focus. If there is more than one control on a page with autofocus set, then the first one added to the page will get focus.
hint_contentOptional[Control]NoneA placeholder Control for the dropdown's value that is displayed when value is None.
select_iconOptional[IconDataOrControl]NoneThe name of the icon or Control to use for the drop-down select button's icon. Defaults to Icon(ft.Icons.ARROW_DROP_DOWN).
elevationNumber8The dropdown's elevation.
menu_border_radiusOptional[BorderRadiusValue]NoneThe radii of the open dropdown menu's rounded rectangle shape. If None (the default), the menu uses its default shape. Note: This shapes the menu only; the input field's border is configured through border.
border_radiusAnnotated[Optional[BorderRadiusValue], V.deprecated('menu_border_radius', version='1.0.0', delete_version='1.3.0', reason='Use menu_border_radius for the menu, or border for the field.', docs_reason='Use :attr:menu_border_radius to shape the menu, or :attr:border to shape the input field.')]NoneThe radii of the open dropdown menu's rounded rectangle shape.
item_heightOptional[Number]NoneThe height of the items/options in the dropdown menu.
max_menu_heightOptional[Number]NoneThe maximum height of the dropdown menu.
select_icon_sizeNumber24.0The size of the icon button which wraps select_icon.
enable_feedbackOptional[bool]NoneWhether detected gestures should provide acoustic and/or haptic feedback. On Android, for example, setting this to True produce a click sound and a long-press will produce a short vibration.
paddingOptional[PaddingValue]NoneThe padding around the visible portion of this dropdown.
select_icon_enabled_colorOptional[ColorValue]NoneThe color of any Icon descendant of select_icon if this button is enabled.
select_icon_disabled_colorOptional[ColorValue]NoneThe color of any Icon descendant of select_icon if this button is disabled.
options_fill_horizontallyboolTrueWhether the dropdown's inner contents to horizontally fill its parent. By default this button's inner width is the minimum size of its content. If True, the inner width is expanded to fill its surrounding container.
disabled_hint_contentOptional[Control]NoneA placeholder Control for the dropdown's value that is displayed when value is None and the dropdown is disabled.
text_sizeOptional[Number]NoneText size in virtual pixels.
text_styleOptional[TextStyle]NoneThe TextStyle to use for the text being edited.
text_vertical_alignOptional[Union[VerticalAlignment, Number]]NoneDefines how the text should be aligned vertically. Value can either be a number ranging from -1.0 (topmost location) to 1.0 (bottommost location) or of type VerticalAlignment Defaults to VerticalAlignment.CENTER.
labelOptional[StrOrControl]NoneOptional text that describes the input field. When the input field is empty and unfocused, the label is displayed on top of the input field (i.e., at the same location on the screen where text may be entered in the input field). When the input field receives focus (or if the field is non-empty) the label moves above, either vertically adjacent to, or to the center of the input field.
label_styleOptional[TextStyle]NoneThe text style to use for label.
iconOptional[IconDataOrControl]NoneThe icon to show before the input field and outside of the decoration's container.
borderOptional[ControlStateValue[InputBorder]]NoneThe border drawn around the decorated input area. Accepts a single InputBorder or a dictionary mapping ControlStates to InputBorders. Supported state keys are DEFAULT, FOCUSED, ERROR, and DISABLED. A single border defines the shape for all states. If its side is unset, the Material theme resolves the border color and weight per state (for example, the focused border uses the theme's primary color); an explicit side applies to the enabled state while the other states remain theme-resolved. In the dictionary form, the DEFAULT entry behaves like the single form, and each state entry without an explicit side falls back to the DEFAULT entry's side, if set.
border_widthAnnotated[Optional[Number], V.deprecated('border', version='1.0.0', delete_version='1.3.0', reason='Use border=OutlineInputBorder(side=BorderSide(width=...)) instead.', docs_reason='Use :attr:border with a :class:~flet.BorderSide instead.')]NoneThe width of the border in virtual pixels.
border_colorAnnotated[Optional[ColorValue], V.deprecated('border', version='1.0.0', delete_version='1.3.0', reason='Use border=OutlineInputBorder(side=BorderSide(color=...)) instead.', docs_reason='Use :attr:border with a :class:~flet.BorderSide instead.')]NoneThe border color.
focused_border_widthAnnotated[Optional[Number], V.deprecated('border', version='1.0.0', delete_version='1.3.0', reason='Use border={ControlState.FOCUSED: OutlineInputBorder(...)} instead.', docs_reason='Use :attr:border with a :attr:flet.ControlState.FOCUSED entry instead.')]NoneBorder width in focused state.
focused_border_colorAnnotated[Optional[ColorValue], V.deprecated('border', version='1.0.0', delete_version='1.3.0', reason='Use border={ControlState.FOCUSED: OutlineInputBorder(...)} instead.', docs_reason='Use :attr:border with a :attr:flet.ControlState.FOCUSED entry instead.')]NoneBorder color in focused state.
colorOptional[ColorValue]NoneText color.
bgcolorOptional[ColorValue]NoneTextField background color. Note: Will not be visible if filled is False.
focused_colorOptional[ColorValue]NoneThe text's color when focused.
focused_bgcolorOptional[ColorValue]NoneBackground color in focused state. Note: Will not be visible if filled is False.
content_paddingOptional[PaddingValue]NoneThe padding for the input decoration's container.
denseOptional[bool]NoneWhether this control is part of a dense form (ie, uses less vertical space).
filledOptional[bool]NoneWhether the decoration's container is filled with fill_color. If filled=None (the default), then it is implicitly set to True when at least one of the following is not None: fill_color, focused_bgcolor, hover_color, and bgcolor.
fill_colorOptional[ColorValue]NoneBackground color of TextField. Note: Will not be visible if filled is False.
focus_colorOptional[ColorValue]NoneThe fill color of the decoration's container when the control has input focus. Note: Text fields usually indicate focus by changing the focused border instead of the fill color. In Flet, prefer focused_bgcolor and a focused border state (e.g. border={ft.ControlState.FOCUSED: ft.OutlineInputBorder(...)}) when you need explicit focused-state styling.
align_label_with_hintOptional[bool]NoneWhether the floating label should align with hint_text. This is typically set to True for multiline text input to align the label with the top of the hint instead of centering it vertically.
hover_colorOptional[ColorValue]NoneBackground color of TextField when hovered. Note: Will not be visible if filled is False.
hint_textOptional[str]NoneText that suggests what sort of input the field accepts. Displayed on top of the input when the it's empty and either (a) label is None or (b) the input has the focus.
hint_styleOptional[TextStyle]NoneThe text style to use for hint_text.
hint_fade_durationOptional[DurationValue]NoneThe duration of the hint_text fade-in and fade-out animations.
hint_max_linesOptional[int]NoneThe maximum number of lines the hint_text can occupy.
helperOptional[StrOrControl]NoneText that provides context about the input's value, such as how the value will be used. If non-null, the text is displayed below the input decorator, in the same location as error. If a non-null error value is specified then the helper text is not shown.
helper_styleOptional[TextStyle]NoneThe text style to use for helper.
helper_max_linesOptional[int]NoneThe maximum number of lines the helper can occupy.
counterOptional[StrOrControl]NoneA Control to place below the line as a character count. If None or an empty string then nothing will appear in the counter's location.
counter_styleOptional[TextStyle]NoneThe text style to use for counter.
errorOptional[StrOrControl]NoneText that appears below the input border. If non-null, the border's color animates to red and the helper is not shown.
error_styleOptional[TextStyle]NoneThe text style to use for error.
error_max_linesOptional[int]NoneThe maximum number of lines the error can occupy. By default, soft line breaks are truncated with an ellipsis while explicit line breaks are respected. Set this property to allow long error text to wrap.
prefixOptional[StrOrControl]NoneA Control to place on the line before the input. It appears after the prefix_icon, if both are specified. This can be used, for example, to add some padding to text that would otherwise be specified using prefix, or to add a custom control in front of the input. The control's baseline is lined up with the input baseline.
prefix_iconOptional[IconDataOrControl]NoneAn icon that appears before the editable part of the text field, within the decoration's container. If prefix is specified and visible, this icon will appear to its left.
prefix_icon_size_constraintsOptional[BoxConstraints]NoneSize constraints for the area surrounding prefix_icon. This can be used to shrink or expand the default icon box. By default, the minimum width and height are 48 pixels, and tighter constraints are commonly used together with a dense decoration.
prefix_styleOptional[TextStyle]NoneThe text style to use for prefix.
suffixOptional[StrOrControl]NoneA Control to place on the line after the input. It appears before the suffix_icon, if both are specified. This can be used, for example, to add some padding to the text that would otherwise be specified using suffix, or to add a custom control after the input. The control's baseline is lined up with the input baseline.
suffix_iconOptional[IconDataOrControl]NoneAn icon that appears after the editable part of the text field and after the suffix, within the decoration's container.
suffix_icon_size_constraintsOptional[BoxConstraints]NoneSize constraints for the area surrounding suffix_icon. This can be used to shrink or expand the default icon box. By default, the minimum width and height are 48 pixels, and tighter constraints are commonly used together with a dense decoration.
size_constraintsOptional[BoxConstraints]NoneDefines the minimum and maximum size of the input decorator.
collapsedOptional[bool]NoneWhether the decoration should be the same size as the input field. A collapsed decoration removes the extra padding normally added by the decorator. Note: Collapsed decorations do not support label, error, counter, icon, prefix, or suffix.
fit_parent_sizeboolFalseWhether the editable area should expand to fill the height of its parent. For controls that support expanding text input, such as TextField, setting this to True expands the editable area to fill the parent and clears the line count constraints. Note: When enabled, min_lines and max_lines must effectively remain unset.
suffix_styleOptional[TextStyle]NoneThe text style to use for suffix.
widthOptional[Number]NoneImposed Control width in virtual pixels.
heightOptional[Number]NoneImposed Control height in virtual pixels.
leftOptional[Number]NoneThe 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, overlay list.
topOptional[Number]NoneThe 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, overlay list.
rightOptional[Number]NoneThe 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, overlay list.
bottomOptional[Number]NoneThe 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, overlay list.
alignOptional[Alignment]NoneAlignment of the control within its parent.
marginOptional[MarginValue]NoneSets the margin of the control.
rotateOptional[RotateValue]NoneTransforms 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: python 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) )
scaleOptional[ScaleValue]NoneScales 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: python 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) )
offsetOptional[OffsetValue]NoneApplies 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: python import flet as ft def main(page: ft.Page): page.add( ft.Stack( width=1000, height=1000, controls=[ ft.Container( bgcolor=ft.Colors.RED, width=100, height=100, left=100, top=100, offset=ft.Offset(-1, -1), ) ], ) ) ft.run(main)
flipOptional[Flip]NoneFlips this control horizontally and/or vertically. Set to an instance of Flip to mirror across x-axis, y-axis, or both.
transformOptional[Transform]NoneApplies a generic matrix transform to this control. Set to an instance of Transform with a recorded Matrix4 to describe arbitrary transform sequences.
aspect_ratioOptional[Number]NoneThe aspect ratio of the control. It is defined as the ratio of width to height. Note: In current implementation, if aspect_ratio is set, width and height on the same control are ignored for final rendered size.
animate_opacityOptional[AnimationValue]None启用 opacity 属性的隐式动画。 详见 此处.
animate_sizeOptional[AnimationValue]None启用此控件尺寸的隐式动画。 If width or height is set, changes to those dimensions are animated. If neither dimension is set, changes to the control's natural size are animated instead. 详见 此处.
animate_positionOptional[AnimationValue]None启用定位属性(left、right、top、bottom)的隐式动画。 详见 此处.
animate_alignOptional[AnimationValue]None启用 align 属性的隐式动画。 详见 此处.
animate_marginOptional[AnimationValue]None启用 margin 属性的隐式动画。 详见 此处.
animate_rotationOptional[AnimationValue]None启用 rotate 属性的隐式动画。 详见 此处.
animate_scaleOptional[AnimationValue]None启用 scale 属性的隐式动画。 详见 此处.
animate_offsetOptional[AnimationValue]None启用 offset 属性的隐式动画。 详见 此处.
size_change_intervalint10Sampling interval in milliseconds for on_size_change event. Setting to 0 calls on_size_change immediately on every change.
expandAnnotated[Optional[Union[bool, int]], V.instance_of((bool, int))]None指定此控件是否/如何扩展以填充父布局中的可用空间。 详见 此处. Note: Has effect only if the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page. Raises: ValueError: If it is not of type bool or int.
expand_looseboolFalse允许控件在主轴方向上有可用空间时扩展,但不要求填满所有可用空间。 详见 此处. Note: 若 expand_loose 为 True,则仅当同时满足以下条件时生效: - expand 不为 None,且 - the direct parent of this control is one of the following controls, or their subclasses: Column, Row, View, Page.
colResponsiveNumber12若此控件的父控件是 ResponsiveRow,此属性用于决定该控件横跨多少个虚拟列。 可以是数字,也可以是为不同断点配置不同值的字典,例如 col={"sm": 6}。 0 表示在该断点下隐藏控件,不占用任何列。 默认横跨 12 个虚拟列。 \
opacityAnnotated[Number, V.between(0.0, 1.0)]1.0定义控件的透明度,取值范围 0.0(完全透明)到 1.0(完全不透明)。 抛出异常:ValueError:若不在 0.0 到 1.0 的闭区间内。
tooltipOptional[TooltipValue]None鼠标悬停时显示的 tooltip。
badgeOptional[BadgeValue]None显示在控件顶部的徽标。
visibleboolTrueEvery control has visible property which is True by default - control is rendered on the page. Setting visible to False 完全阻止该控件(及其所有子控件)渲染到页面画布上. 隐藏的控件不能通过键盘或鼠标聚焦或选中,也不会触发任何事件。
disabledboolFalseEvery 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: python ft.Column( disabled = True, controls=[ ft.TextField(), ft.TextField() ] )
rtlboolFalse控件的文字方向是否为从右到左(RTL)。
dataAnyskip_任意类型的自定义数据。
keyOptional['KeyValue']None用于在更新之间保持控件身份稳定的 key。

只读属性 ​

名称类型默认值说明
parentOptional['BaseControl']—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). Page 控件(树的根)为例外 —— 它始终 parent=None。
page'Page'—此控件所属的页面。

事件 ​

名称类型默认值说明
on_changeOptional[ControlEventHandler['DropdownM2']]NoneCalled when the selected item of this dropdown has changed.
on_focusOptional[ControlEventHandler['DropdownM2']]NoneCalled when the control has received focus.
on_blurOptional[ControlEventHandler['DropdownM2']]NoneCalled when the control has lost focus.
on_clickOptional[ControlEventHandler['DropdownM2']]NoneCalled when this dropdown is clicked.
on_size_changeOptional[EventHandler[LayoutSizeChangeEvent['LayoutControl']]]NoneCalled when the size of this control changes. size_change_interval defines how often this event is called.
on_animation_endOptional[ControlEventHandler['LayoutControl']]None动画结束时调用,可用于串联多个动画。 事件参数 data 属性包含动画的名称。 详见 此处.

方法 ​

名称类型默认值说明
before_update———
focus——Request focus for this control. Example: python async def main(page: ft.Page): page.add(ctf := ft.TextField()) await ctf.focus()
is_isolated——Return whether this control is marked as isolated. 被隔离的控件不会参与父级驱动的更新遍历,需要自行管理更新边界。
init——Called after control instance initialization and before the first build / update cycle. 可重写此钩子执行依赖于已初始化字段的轻量设置。 不要在这里调用 update()。
build——在控件初始化期间调用一次,用于定义其子控件。 page 属性在此方法中可用。
before_event——在事件处理器执行前拦截事件。 返回 False 取消分发,返回 True 或 None 则继续正常的事件处理。
did_mount——在控件挂载到页面树之后调用。 可重写以启动需要已挂载页面的资源,例如订阅、定时器或服务监听。
will_unmount——在控件从页面树移除之前调用。 可重写以释放 did_mount() 中创建的资源,例如订阅、定时器或外部句柄。
get_data_channel——Resolve the [DataChannel] allocated on the Dart side for this widget. Pattern: on_data_channel_open: Optional[ft.EventHandler[DataChannelOpenEvent]] = None def init(self): self.on_data_channel_open = self._on_open def _on_open(self, e): self._channel = self.get_data_channel(e.channel_id) Idempotent — the underlying Connection caches DataChannels by id, so repeated calls return the same instance. No error path: the id always comes from a framework-fired event, so by the time this runs the channel exists on both sides.
updateNone—请求更新该控件的 UI。 在修改控件状态或属性后调用。 控件必须已挂载到页面,并且未被冻结。

示例 ​

Field border and menu shape ​

python
import flet as ft


def main(page: ft.Page):
    page.add(
        ft.SafeArea(
            content=ft.Column(
                controls=[
                    ft.DropdownM2(
                        label="Matching field and menu",
                        value="a",
                        border=ft.OutlineInputBorder(
                            border_radius=20,
                            side=ft.BorderSide(width=2, color=ft.Colors.TEAL),
                        ),
                        menu_border_radius=20,
                        options=[
                            ft.dropdownm2.Option("a", "Alice"),
                            ft.dropdownm2.Option("b", "Bob"),
                            ft.dropdownm2.Option("c", "Carol"),
                        ],
                    ),
                    ft.DropdownM2(
                        label="Underlined field, rounded menu",
                        value="a",
                        border=ft.UnderlineInputBorder(),
                        menu_border_radius=ft.BorderRadius.only(
                            bottom_left=16, bottom_right=16
                        ),
                        options=[
                            ft.dropdownm2.Option("a", "Alice"),
                            ft.dropdownm2.Option("b", "Bob"),
                            ft.dropdownm2.Option("c", "Carol"),
                        ],
                    ),
                ],
            ),
        ),
    )


if __name__ == "__main__":
    ft.run(main)

关注我,学习大模型、大数据、Python等热门技术。