SharedPreferences

Provides access to persistent key-value storage.

Inherits from flet.Service.

Methods

  • **clear()** async:
  • * Description: Clears all keys and values. * Returns: bool

  • **contains_key(key: str)** async:
  • * Description: Checks if the given key exists. * Parameters: * key (str): The key to check. * Returns: bool

  • **get(key: str)** async:
  • * Description: Gets the value for the given key. * Parameters: * key (str): The key whose value to retrieve.

  • **get_keys(key_prefix: str)** async:
  • * Description: Gets all keys with the given prefix. * Parameters: * key_prefix (str): The prefix to filter keys. * Returns: list[str]

  • **remove(key: str)** async:
  • * Description: Removes the value for the given key. * Parameters: * key (str): The key to remove. * Returns: bool

  • **set(key: str, value: Any)** async:
  • * Description: Sets a value for the given key. * Parameters: * key (str): The key to set. * value (Any): The value to store. * Returns: bool

    Examples

    Basic Example

    import flet as ft

    async def main(page: ft.Page): async def set_value(): await ft.SharedPreferences().set(store_key.value, store_value.value) get_key.value = store_key.value store_key.value = "" store_value.value = "" page.show_dialog(ft.SnackBar("Value saved to SharedPreferences"))

    async def get_value(): contents = await ft.SharedPreferences().get(get_key.value) page.add(ft.Text(f"SharedPreferences contents: {contents}"))

    page.add( ft.Column( [ ft.Row( [ store_key := ft.TextField(label="Key"), store_value := ft.TextField(label="Value"), ft.Button("Set", on_click=set_value), ] ), ft.Row( [ get_key := ft.TextField(label="Key"), ft.Button("Get", on_click=get_value), ] ), ], ) )

    ft.run(main)