Skip to content

Magnetometer

Streams magnetometer readings reporting the ambient magnetic field (uT) per axis for compass-style use cases.

Note

Supported platforms: Android, iOS. Magnetometer APIs are not available on Web or desktop, so always handle on_error to detect unsupported hardware.

Inherits: Service

Properties

Events

Examples#

import flet as ft


def main(page: ft.Page):
    intro = ft.Text("Monitor the ambient magnetic field (uT).")
    reading = ft.Text("Waiting for data...")

    def handle_reading(e: ft.MagnetometerReadingEvent):
        reading.value = f"x={e.x:.2f} uT, y={e.y:.2f} uT, z={e.z:.2f} uT"
        page.update()

    def handle_error(e: ft.SensorErrorEvent):
        page.add(ft.Text(f"Magnetometer error: {e.message}"))

    page.session.store.set(
        "magnetometer_service",
        ft.Magnetometer(
            on_reading=handle_reading,
            on_error=handle_error,
            interval=ft.Duration(milliseconds=200),
        ),
    )

    page.add(intro, reading)


ft.run(main)

Properties#

cancel_on_error class-attribute instance-attribute #

cancel_on_error: bool = True

Whether the stream subscription should cancel on the first sensor error.

enabled class-attribute instance-attribute #

enabled: bool = True

Whether the sensor should be sampled. Disable to stop streaming.

interval class-attribute instance-attribute #

interval: Duration | None = None

Desired sampling interval provided as a Duration. Defaults to 200 ms.

Events#

on_error class-attribute instance-attribute #

on_error: EventHandler[SensorErrorEvent] | None = None

Fired when the platform reports a sensor error. event.message is the error description.

on_reading class-attribute instance-attribute #

on_reading: (
    EventHandler[MagnetometerReadingEvent] | None
) = None

Fires when a new reading is available.

event contains x, y, z magnetic field strengths (uT) and timestamp (microseconds since epoch).