Skip to content

Conversation

@ndonkoHenri
Copy link
Contributor

@ndonkoHenri ndonkoHenri commented Nov 8, 2025

Fix #5185

Example

from datetime import time

import flet as ft


def main(page: ft.Page):
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    def get_system_hour_format():
        """Returns the current system's hour format."""
        return "24h" if page.media.always_use_24_hour_format else "12h"

    def format_time(value: time) -> str:
        """Returns a formatted time string based on TimePicker and system settings."""
        use_24h = time_picker.hour_format == ft.TimePickerHourFormat.H24 or (
            time_picker.hour_format == ft.TimePickerHourFormat.SYSTEM
            and page.media.always_use_24_hour_format
        )
        return value.strftime("%H:%M" if use_24h else "%I:%M %p")

    def handle_change(e: ft.Event[ft.TimePicker]):
        selection.value = f"Selection: {format_time(time_picker.value)}"

    time_picker = ft.TimePicker(
        value=time(hour=9, minute=30),
        help_text="Choose your meeting time",
        on_change=handle_change,
    )

    def open_picker(e: ft.Event[ft.Button]):
        choice = format_dropdown.value
        hour_format_map = {
            "system": ft.TimePickerHourFormat.SYSTEM,
            "12h": ft.TimePickerHourFormat.H12,
            "24h": ft.TimePickerHourFormat.H24,
        }
        time_picker.hour_format = hour_format_map[choice]
        page.show_dialog(time_picker)

    page.add(
        ft.Row(
            alignment=ft.MainAxisAlignment.CENTER,
            controls=[
                format_dropdown := ft.Dropdown(
                    label="Hour format",
                    value="system",
                    width=260,
                    options=[
                        ft.DropdownOption(
                            key="system",
                            text=f"System default ({get_system_hour_format()})",
                        ),
                        ft.DropdownOption(key="12h", text="12-hour clock"),
                        ft.DropdownOption(key="24h", text="24-hour clock"),
                    ],
                ),
                ft.Button(
                    "Open TimePicker",
                    icon=ft.Icons.SCHEDULE,
                    on_click=open_picker,
                ),
            ],
        ),
        selection := ft.Text(weight=ft.FontWeight.BOLD),
    )


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

Summary by Sourcery

Enable custom hour formatting in TimePicker by introducing a new hour_format option and propagating the platform's 24-hour preference, refactor entry_mode API, and update documentation and tests accordingly

New Features:

  • Add TimePickerHourFormat enum and hour_format property to allow selecting system, 12h, or 24h display modes
  • Expose always_use_24_hour_format in PageMediaData and apply it via MediaQuery to honor platform time format settings

Enhancements:

  • Rename time_picker_entry_mode to entry_mode across Python and Dart implementations
  • Wrap TimePicker dialog in MediaQuery for proper 24-hour format rendering
  • Change show_dialog to raise RuntimeError when opening an already open dialog

Documentation:

  • Document the new TimePickerHourFormat and add an hour formats example to the TimePicker docs

Tests:

  • Add integration and screenshot tests covering basic, 12h, 24h, and system hour format behaviors

@ndonkoHenri ndonkoHenri changed the title feat: custom TimePicker time formats feat: custom TimePicker hour formats Nov 8, 2025
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've reviewed this pull request using the Sourcery rules engine

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Nov 8, 2025

Deploying flet-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 493dd99
Status: ✅  Deploy successful!
Preview URL: https://a3802eaa.flet-docs.pages.dev
Branch Preview URL: https://timepicker-time-format.flet-docs.pages.dev

View logs

@ndonkoHenri
Copy link
Contributor Author

ndonkoHenri commented Nov 8, 2025

Two issues left:

  • running basic.py example and changing the entry mode from the UI, I get an unexpected AttributeError: 'TimePickerEntryModeChangeEvent' object has no attribute 'entry_mode' - (ref)
  • integration_tests/examples/material/test_time_picker.py::test_hour_formats fails with an unexpected RuntimeError: The finder "Found 2 widgets with text "12-hour clock", though we have only one on the UI. (ref)

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds support for controlling the hour format (12-hour vs 24-hour) in the TimePicker control. The implementation introduces a new TimePickerHourFormat enum with three values: SYSTEM, H12, and H24, and adds a corresponding hour_format property to the TimePicker control.

Key changes:

  • New TimePickerHourFormat enum with system/12h/24h options
  • Updated TimePicker with hour_format property and improved documentation
  • Added always_use_24_hour_format to PageMediaData for system-level hour format detection
  • Enhanced documentation with examples demonstrating hour format usage

Reviewed Changes

Copilot reviewed 16 out of 22 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
sdk/python/packages/flet/src/flet/controls/theme.py Fixed Markdown link syntax in docstrings for TextStyle references
sdk/python/packages/flet/src/flet/controls/material/time_picker.py Added TimePickerHourFormat enum, updated TimePicker class with hour_format property and improved documentation
sdk/python/packages/flet/src/flet/controls/base_page.py Added always_use_24_hour_format field to PageMediaData
sdk/python/packages/flet/src/flet/__init__.py Exported new TimePickerHourFormat enum
sdk/python/packages/flet/mkdocs.yml Added documentation page for TimePickerHourFormat
sdk/python/examples/controls/time_picker/basic.py Updated example with improved code quality
sdk/python/examples/controls/time_picker/hour_formats.py New example demonstrating hour format functionality
packages/flet/lib/src/controls/time_picker.dart Dart implementation for hour format support using MediaQuery
packages/flet/lib/src/protocol/page_media_data.dart Added alwaysUse24HourFormat field to protocol
packages/flet/lib/src/widgets/page_media.dart Updated to read alwaysUse24HourFormat from MediaQuery
Integration test files Added comprehensive tests for different hour formats

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@FeodorFitsner
Copy link
Contributor

  1. Merge main and resolve conflicts.
  2. Getting this error while running time_picker/basic.py example:
Exception in 'on_entry_mode_change': 'TimePickerEntryModeChangeEvent' object has no attribute 'entry_mode'
Traceback (most recent call last):
  File "/Users/feodor/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/messaging/session.py", line 193, in dispatch_event
    await control._trigger_event(event_name, event_data)
  File "/Users/feodor/projects/flet-dev/flet/sdk/python/packages/flet/src/flet/controls/base_control.py", line 328, in _trigger_event
    event_handler(e)
  File "/Users/feodor/projects/flet-dev/flet/sdk/python/examples/controls/time_picker/basic.py", line 18, in handle_entry_mode_change
    print(e, e.entry_mode)
             ^^^^^^^^^^^^
AttributeError: 'TimePickerEntryModeChangeEvent' object has no attribute 'entry_mode'

ndonkoHenri and others added 11 commits November 11, 2025 00:15
# Conflicts:
#	sdk/python/packages/flet/integration_tests/controls/material/test_time_picker.py
#	sdk/python/packages/flet/integration_tests/examples/material/test_time_picker.py
Enhanced the tester API to allow specifying the index of a control when multiple matches are found. Updated Dart and Python tester interfaces, finder logic, and integration tests to support and utilize this capability, enabling more precise UI automation and testing.
The call to resize_page in test_hour_formats is no longer awaited, likely because the function is now synchronous. This aligns the test with the updated API.
Refreshed golden images for macOS time picker hour formats and added new images for additional formats. Modified test_time_picker.py to improve the _select_clock helper, ensuring more comprehensive screenshot coverage and interaction consistency.
Refreshed the golden PNG images for basic, 12-hour, and 24-hour time picker integration tests on macOS to reflect recent UI or rendering changes.
Refreshed basic.png and image_for_docs.png in the golden images for the macOS time picker integration tests to reflect recent UI or rendering changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TimePicker 12 hour format

3 participants