App State

App State variables are global variables that live at the highest level of your application. They are accessible from any page and any component in your project.

spinner

Watch this on Youtube: https://www.youtube.com/watch?v=lZ2hGiaVBVYarrow-up-right

Lifecycle & Persistence

App State variables live as long as the application is running. However, you can choose to make them survive even after the app is closed using Persistence.

  • Non-Persisted: Value is lost when the app is closed (cleared from memory).

  • Persisted: Value is saved to the device's disk (Key-Value storage). It is automatically reloaded when the app restarts.

[!IMPORTANT] Key-Value Storage: Persisted state is backed by simple key-value storage (like Shared Preferences).

  • Do NOT treat it like a database. You cannot query it.

  • Do NOT store massive datasets.

When to use App State?

Choose App State when data needs to:

  1. Survive Navigation: Data shouldn't be lost when moving from Page A to Page B.

  2. Be Shared: Multiple screens need access to the same data (e.g., a Shopping Cart).

  3. Persist: You want to remember the data even after the user closes the app (e.g., authToken, isDarkMode).

How to Create App State Variables

  1. Open the App Settings panel (usually the gear icon).

  2. Select the App State tab.

  3. Click + Add State Variable.

  4. Define the Name, Type, and Default Value.

How to Use App State

There are two primary ways to consume App State in your UI:

1. Expressions (Passive)

Use this when you just need to read the value at a specific moment, or if the widget handles updates internally.

  • Usage: Bind a Text widget's value to appState.userName.

2. StreamBuilder (Reactive)

App State exposes a Stream of changes. If you want your UI to automatically rebuild whenever the variable changes, you must "listen" to it.

  • Usage: Wrap your widget in a StreamBuilder.

  • Source: Select the specific App State variable as the stream source.

Goal
Method

Just display a value

Expression

Update UI instantly when value changes

StreamBuilder

Updating App State

To change the value of a global variable, use the Set App State action.

Best Practices

[!TIP]

  • Naming: Use clear prefixes like is for Booleans (isLoggedIn) or has (hasSeenOnboarding).

  • Reset on Logout: If you store user data in App State, remember to specific an action to Clear/Reset these variables when the user logs out.

Last updated