SharedPreferences
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)
Methods#
clear
async
#
clear() -> bool
Clears all keys and values.
Returns:
-
bool–Trueif the preferences were cleared successfully,Falseotherwise.
contains_key
async
#
get
async
#
get(key: str) -> SharedPreferencesValueType | None
Gets the value for the given key.
Parameters:
-
key(str) –The key to retrieve the value for.
Returns:
-
SharedPreferencesValueType | None–The value for the given key, or
Noneif the key doesn't exist.
get_keys
async
#
remove
async
#
set
async
#
Sets a value for the given key.
Note
Due to limitations on Android, it is not possible to set values that start
with any of the following: VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu,
VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy, and
VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu.
Parameters:
-
key(str) –The key to store the value under.
-
value(SharedPreferencesValueType) –The value to store.
Returns:
-
bool–Trueif the value was set successfully,Falseotherwise.
Raises:
-
ValueError–If
valueis of an unsupported type (str,int,float,bool, andlist[str]).