ssr library

Server-Side Rendering module for Lark.

This module provides server-safe APIs for rendering Lark components on the Dart VM. It can be used with any Dart server framework (Shelf, Alfred, Dart Frog, etc.).

import 'package:lark/ssr.dart';
import 'package:shelf/shelf.dart';

Response handleRequest(Request request) async {
  final app = LarkApp(routes: routes);
  final result = await renderToHtml(
    app,
    path: request.url.path,
    query: request.url.queryParameters,
  );

  return Response.ok(
    result.toDocument(title: 'My App'),
    headers: {'content-type': 'text/html'},
  );
}

Classes

App
The main Lark application runner.
AppConfig
Application configuration loaded from environment.
AppRunner
VM-safe stub for the web app runner.
AppShell
Internal shell for routing.
BaseEntry
The base href tag.
BlankLayout
A layout that just renders the page without wrapping.
Box
Generic div wrapper.
BuildConfig
Build configuration.
CheckboxBase
Base checkbox.
Color
A color represented by RGBA values.
Colors
Common colors.
Column
A vertical flex container.
Component
Abstract base class for all Lark UI components.
ComponentInfo
Information about a registered component.
ComponentNode
A node in the component tree.
ComponentRegistry
Registry of all mounted Component instances.
ComponentSnapshot
Snapshot of a component tree.
ComponentTree
The full component tree.
Computed<T>
A cached derived value that automatically tracks dependencies.
Constraints
Immutable box constraints.
Container
A generic layout container.
ContentItem
A single item in the content catalog.
ContentItemSection
Represents a section extracted from document headings (## and ###).
ContentQuery
Query builder for Lark Content.
CookieOptions
Cookie options.
CookieStorage
Cookie storage abstraction.
Debounced<T>
Result type for useDebounce.
DevMessageV2
Enhanced dev message with granular update information.
DevTools
Developer tools manager.
DevToolsState
Tracks all reactive state for DevTools inspection.
DialogController
Overlay visibility controller.
DismissableLayer
Layer that can be dismissed by outside interaction.
Effect
A reactive side effect that re-runs when dependencies change.
Empty
A component that renders nothing.
Env
Environment access.
ErrorBoundary
A component that catches errors in its children.
ErrorContext
Error context for reporting.
ErrorReport
Error report for tracking.
ErrorReporter
Error reporting configuration.
Expanded
Expands child in a flex context.
FieldDef
Defines a form field.
FocusScope
Focus scope container.
FocusTrap
Focus trap container.
Form
Base form container.
FormField<T>
Reactive state for a single form field.
FormState
Reactive form with validation and submit handling.
Fragment
Groups children without adding structure.
GoogleFont
Configuration for a single Google Font.
GoogleFontsEngine
Engine for generating Google Fonts links and scanning CSS.
Grid
A grid container.
Head configuration object for LarkApp.
HeadEntry
Base class for all head entries.
HeadManager
Central manager for all head tags.
HmrState
HMR state manager for preserving state across hot reloads.
HoverRegion
Hover interaction region.
HtmlElement
Base class for HTML elements.
HtmlRenderer
Renders a component tree to HTML string.
HttpResponse
Simple HTTP response wrapper.
Hydration
Manages hydration from SSG to SPA.
Icon
Displays an icon from Lucide (default) or custom icon fonts.
Icons
Lucide icon names - 1666 icons.
IdProvider
ID scope wrapper.
Image
Displays an image.
InputBase
Base text input.
InputDecoration
Decoration metadata for consistent form field presentation.
Label
Label primitive for base forms.
LarkApp
The root component for a Lark application.
LarkColors
Helper for defining colors.
LarkConfig
Lark application configuration.
LarkContent
Access point for Lark Content.
LarkRuntime
Abstract runtime that all Lark platforms implement.
LarkServerRenderer
Renders Lark applications on the server.
Layout
Base class for layouts that wrap pages.
A navigation link.
LinkEntry
A link tag.
LiveRegion
Live region accessibility primitive.
LogConfig
Global logging configuration.
Logger
A logger instance.
Markdown
Renders Markdown content as HTML.
MemoryPlatformStorage
In-memory storage implementation for server/test.
MemoryStorage
In-memory storage fallback (for SSR or testing).
Menu visibility controller.
MetaEntry
A meta tag.
MiddlewareRunner
Middleware runner that executes a chain of middleware.
MutationOptions<TData, TVariables, TContext>
Configuration options for a mutation.
Navigation binding for platform-specific routing.
Controls navigation flow in middleware.
NetworkRequest
A captured network request.
NetworkTracker
Tracks network requests for DevTools.
NoOpNavigationBinding
No-op navigation binding for server/test environments.
NoOpStorageBinding
No-op storage binding using memory storage.
OptionBase<T>
Base option model for SelectBase.
Overlay
Generic overlay primitive.
OverlayConfig
Overlay behavior config attached to a rendered vnode.
PageResult<T>
Page result from fetcher.
Paragraph
Paragraph primitive.
PerformanceMetrics
Performance metrics collector.
PersistenceAdapter
Interface for store persistence (localStorage, etc).
PlatformRenderer
Interface for platform-specific renderers.
PlatformStorage
Abstract storage interface.
Portal
Portal primitive.
Pressable
Unstyled button-like primitive.
Previous<T>
Result type for usePrevious.
PrimitiveComponent
Marker interface for primitive components (leaf nodes).
Provider<T>
Provides a value to descendant components.
ProvideRef<T>
Provides a reactive ref to descendants.
QueryClient
Central manager for query caching and invalidation.
QueryOptions<T>
Configuration options for a query.
RadioBase<T>
Base radio.
ReactiveNode
Represents a node in the reactive dependency graph.
ReactiveScope
Manages the current reactive subscriber context.
ReadonlyRef<T>
Read-only component of a reactive ref.
Ref<T>
A reactive container that holds a value and notifies on change.
RefSnapshot
Snapshot of a ref for DevTools display.
RenderContext
Render context for SSR.
RenderNode
Abstract render node that can layout and paint itself.
RenderResult
Result of server-side rendering.
Route
Represents a route in the application.
RouteCollection
Route collection for matching.
RouteDefinition
Defines a route with path pattern and builder.
RouteMatch
Result of matching a URL against a route.
Router
The application router.
RouterComponent
A component that renders the matched route's component.
A link that navigates via the router without reloading the page.
RouterOutlet
A component that renders the nested route based on the current depth.
RovingFocusGroup
Basic roving-focus wrapper.
Row
A horizontal flex container.
ScriptEntry
A script tag.
ScrollController
Imperative controller for a ScrollView.
ScrollView
A scrollable viewport container.
SelectBase<T>
Base select.
ServerInit
ServerRenderer
Abstract server renderer interface.
ServerRuntime
Server runtime implementation.
Size
Immutable size representation.
Slot
Slot primitive for composition.
SourceLocation
Source location for error reporting.
Spacer
Unstyled spacing primitive.
Stack
A layered layout container.
StateChange
A state change event.
Storage
Abstract storage interface (implemented differently for web/server).
StorageBinding
Storage binding for platform-specific persistence.
Style
A record type containing all supported CSS properties.
StyleEntry
An inline style tag.
StyleRegistry
Subscriber
Represents a reactive consumer that can be notified of dependency changes.
SubscriberStats
Tracks statistics about a subscriber for debugging and profiling.
Svg
Displays an SVG image.
TailwindConfig
Configuration for the Tailwind engine.
Text
Text span primitive.
TextareaBase
Base textarea.
TextFieldBinding
Binding callbacks for wiring a FormField into input components.
TextLeaf
Internal text leaf node.
Theme
Theme definition containing design tokens.
ThemeColors
Color tokens for theming.
ThemeConfig
Defines a strongly-typed theme configuration for Lark Tailwind.
ThemeProvider
Theme provider wrapper.
ThemeRadius
Border radius tokens.
ThemeShadows
Shadow tokens.
ThemeSpacing
Spacing tokens.
ThemeTypography
Typography tokens.
ThemeZIndex
Z-index tokens.
TimelineEntry
A single entry on the timeline.
TimelineEvent
Timeline event for debugging.
TimelineProfiler
Performance timeline profiler for DevTools.
TimelineRecording
A complete timeline recording session.
TitleEntry
The page title.
Toggle
Result type for useToggle.
TooltipController
Tooltip visibility controller.
UrlResolver
Normalizes and resolves asset URLs.
VDomBuilder
Builds VNodes from Lark Components.

Enums

AlignContent
Values for align-content property.
AlignItems
Values for align-items property.
AlignSelf
Values for align-self property.
AnimationDirection
Values for animation-direction property.
AnimationFillMode
Values for animation-fill-mode property.
AnimationPlayState
Values for animation-play-state property.
AutovalidateMode
Mirrors Flutter's autovalidation behavior.
BackfaceVisibility
Values for backface-visibility property.
BackgroundAttachment
Values for background-attachment property.
BackgroundClip
Values for background-clip property.
BackgroundOrigin
Values for background-origin property.
BackgroundRepeat
Values for background-repeat property.
BackgroundSize
Values for background-size property (keywords only).
BlendMode
Values for background-blend-mode and mix-blend-mode properties.
BorderCollapse
Values for border-collapse property.
BorderStyle
Values for border style properties.
BoxSizing
Values for box-sizing property.
CaptionSide
Values for caption-side property.
Clear
Values for clear property.
ColorScheme
Dark mode preference.
CssTextAlign
Values for text-align property.
Cursor
Values for cursor property.
DarkMode
Dark mode strategy for Tailwind.
DevMessageSeverity
Severity levels for dev messages.
DevMessageType
Types of dev messages.
Direction
Values for direction property.
Display
Values for display property.
EmptyCells
Values for empty-cells property.
FetchStatus
Detailed fetch status for distinguishing types of loading.
FlexDirection
Values for flex-direction property.
FlexWrap
Values for flex-wrap property.
Float
Values for float property.
FontKerning
Values for font-kerning property.
FontStretch
Values for font-stretch property.
FontStyle
Values for font-style property.
FontVariant
Values for font-variant property.
FontWeight
Values for font-weight property (keywords only).
GridAutoFlow
Values for grid-auto-flow property.
HeadCategory
Tag categories for grouping and deduplication.
HeadLayer
Priority layers for tag resolution. Higher priority layers override lower ones for tags with the same key.
HydrationState
Hydration state.
Hyphens
Values for hyphens property.
ImageFit
ImageRendering
Values for image-rendering property.
InputType
Native input type choices.
Isolation
Values for isolation property.
JustifyContent
Values for justify-content property.
ListStylePosition
Values for list-style-position property.
ListStyleType
Values for list-style-type property.
LogLevel
Log levels.
NetworkRequestStatus
Status of a network request.
ObjectFit
Values for object-fit property.
Overflow
Values for overflow properties.
OverlayAlign
Overlay positioning alignment.
OverlaySide
Overlay positioning side.
PageBreak
Values for page-break-after and page-break-before properties.
PageBreakInside
Values for page-break-inside property.
PointerEvents
Values for pointer-events property.
Position
Values for position property.
QueryStatus
The current status of a query.
RenderTarget
How to render the application.
Resize
Values for resize property.
RovingOrientation
Roving focus group orientation.
RuntimeType
The runtime environment.
ScrollAxis
Scroll axes for ScrollView.
ScrollBehavior
Values for scroll-behavior property.
SpacerAxis
Axis options for Spacer.
StateChangeType
Type of state change event.
TableLayout
Values for table-layout property.
TextAlignLast
Values for text-align-last property.
TextDecorationLine
Values for text-decoration-line property.
TextDecorationStyle
Values for text-decoration-style property.
TextInputAction
Describes action semantics for Enter/submit behavior.
TextJustify
Values for text-justify property.
TextOverflow
Values for text-overflow property (keywords only).
TextTransform
Values for text-transform property.
TimelineEntryType
Type of timeline entry.
TransformStyle
Values for transform-style property.
UserSelect
Values for user-select property.
Visibility
Values for visibility property.
WhiteSpace
Values for white-space property.
WordBreak
Values for word-break property.
WordWrap
Values for word-wrap / overflow-wrap property.
WritingMode
Values for writing-mode property.

Extension Types

DartLoader

Extensions

RenderContextAccess on RenderContext
Extension to access current context from zone.

Constants

serverInit → const ServerInit
Marks a method to run on the server before rendering.

Properties

appLog Logger
Global app logger.
final
defaultFormatterCatalog Map<String, NamedFormatterFactory>
Built-in named formatter factories for schema forms.
final
defaultFormValidatorCatalog Map<String, NamedFormValidatorFactory>
Built-in named form validator factories for schema forms.
final
defaultValidatorCatalog Map<String, NamedValidatorFactory>
Built-in named validator factories for schema forms.
final
devTools DevTools
Shorthand to access devtools.
no setter
digitsOnly ValueFormatter
Keeps only digits from string input.
getter/setter pair
email Validator
Validates email format.
getter/setter pair
env Env
Global env instance.
final
hasRuntime bool
Whether a runtime has been configured.
no setter
hotReloadVersion Ref<int>
Global signal that increments whenever a hot reload occurs.
final
isDev bool
Convenience getters.
no setter
isHydrated bool
Whether hydration is complete.
no setter
isHydrating bool
Whether currently hydrating.
no setter
isProd bool
no setter
isTest bool
no setter
localStorage Storage
Get localStorage (falls back to memory storage).
no setter
lowercase ValueFormatter
Converts string input to lowercase.
getter/setter pair
queryClient QueryClient
Global query client instance.
final
required Validator
Requires a non-empty value.
getter/setter pair
runtime LarkRuntime
Gets the current runtime.
no setter
sessionStorage Storage
Get sessionStorage (falls back to memory storage).
no setter
storeRefRegistry Map<String, List<(String, Ref)>>
Read-only access to the store refs (for HMR).
no setter
storeRegistry Map<String, dynamic>
Read-only access to the store registry (for HMR and dev tools).
no setter
styleRegistry StyleRegistry
Global style registry.
final
trim ValueFormatter
Trims string input.
getter/setter pair
uppercase ValueFormatter
Converts string input to uppercase.
getter/setter pair

Functions

batch<T>(T fn()) → T
Groups multiple ref updates into a single notification cycle.
clearAllStores() → void
Clears all stores.
clearStore(String name) → void
Clears a store (useful for testing or logout).
cn(List classes) String
computed<T>(T compute(), {EqualityFn<T>? equals, String? name}) Computed<T>
Creates a new computed value that automatically tracks dependencies.
configureCookies(CookieStorage storage) → void
Configure cookie storage.
configureDarkModeAutoApply(void apply(bool isDark)) → void
Configure auto-application of dark mode class.
configureDarkModeDefaultPreference(ColorScheme preference) → void
Configure the default preference used when nothing is stored yet.
configureDarkModeDetection(bool detector()) → void
Configure system preference detection.
configureDarkModeDomSync({required bool enabled}) → void
Enable/disable applying dark class updates to the DOM.
configureDarkModeSystemObserver(void Function()? observer(void onChange(bool isDark))) → void
Configure system preference observation for live updates.
configureFetch({required HttpGet get, required HttpPost post}) → void
Configure the HTTP client for fetch operations.
configureRuntime(LarkRuntime rt) → void
Configure the runtime (called by platform entry points).
configureStorage({Storage? local, Storage? session}) → void
Configure storage for the platform.
createApp(LarkApp root) AppRunner
createCounterStore(String name, {int initial = 0}) → ({Ref<int> count, void Function() decrement, void Function() increment, void Function() reset}) Function()
Creates a simple counter store.
createLogger(String name) Logger
Creates a logger for a component.
createSsgApp(Component root, {RenderTarget target = RenderTarget.html}) App
Creates a Lark app for SSG (static site generation).
createToggleStore(String name, {bool initial = false}) → ({void Function() setFalse, void Function() setTrue, void Function() toggle, Ref<bool> value}) Function()
Creates a simple toggle store.
custom(String? fn(dynamic value)) Validator
Custom validator.
cva({String? base, Map<String, Map<String, String>>? variants, List<Map<String, dynamic>>? compoundVariants, Map<String, String>? defaultVariants}) VariantFunction
Creates a variant configuration function.
defineStore<T>(String name, T setup(), {bool persist = false}) → T Function()
Defines a reactive store.
effect(EffectFn fn, {String? name}) → void Function()
Creates and runs a new reactive effect.
field({dynamic initialValue, List<Validator> validators = const [], List<AsyncValidator> asyncValidators = const [], List<ValueFormatter> formatters = const [], AutovalidateMode? autovalidateMode, Duration asyncDebounce = const Duration(milliseconds: 300), void onSaved(dynamic value)?, Map<String, dynamic> meta = const {}}) FieldDef
Creates a field definition.
fieldsMatch(String left, String right, {String message = 'Values do not match'}) FormValidator
Requires two fields to match, useful for confirm-password checks.
getMiddleware(String name) MiddlewareFn?
Gets a registered middleware by name.
getMiddlewareList(List<String> names) List<MiddlewareFn>
Gets multiple middleware by names.
hydrateApp(Component root, String selector) Future<void>
Hydrates an SSG pre-rendered app.
max(num n, {String? message}) Validator
Requires a maximum numeric value.
maxChars(int length) ValueFormatter
Limits string length.
maxLength(int n) Validator
Requires maximum length.
min(num n, {String? message}) Validator
Requires a minimum numeric value.
minLength(int n) Validator
Requires minimum length.
onMount(CleanupFn? fn()) → void Function()
Creates an effect that only runs once on mount.
onStoreInit(void callback(String)) → void
Register a callback to be called when a store is initialized.
pattern(RegExp regex, {String message = 'Invalid format'}) Validator
Validates against a regex pattern.
propertiesToCss(Style props) String
ref<T>(T initialValue, {EqualityFn<T>? equals, String? name}) Ref<T>
Creates a new reactive ref with the given initial value.
registerMiddleware(String name, MiddlewareFn middleware) → void
Registers a named middleware.
registerStoreRef(Ref r, String? name) → void
renderPage(Component component, {String? title, String? lang = 'en', bool pretty = false}) String
Renders a full HTML page with meta tags.
renderToHtml(Component root, {required String path, Map<String, String>? query, Map<String, String>? headers, bool pretty = false}) Future<RenderResult>
Render a component to HTML string.
renderToString(Component component, {bool pretty = false}) String
Renders a component to HTML string (SSG).
reportError(Object error, [StackTrace? stackTrace, String? context]) → void
Reports an error with optional context.
resetDarkModeSystemTrackingForTesting() → void
Test helper to reset cached system dark mode tracking state.
route(String path, Component builder(Map<String, String> params), {String? name, List<String> middleware = const [], List<RouteDefinition> children = const [], FutureOr<Object?> loader(RouteMatch match)?, Map<String, dynamic> meta = const {}}) RouteDefinition
Creates route definitions.
runWithContext<T>(RenderContext context, Future<T> fn()) Future<T>
Run a function with a render context.
runWithHeadManager<T>(HeadManager manager, T fn()) → T
Run a function with a specific HeadManager.
runWithRouter<T>(Future<T> fn(Router router)) Future<T>
Run a function with an isolated Router instance.
setPersistenceAdapter(PersistenceAdapter adapter) → void
Sets the persistence adapter.
setRefRegistrationCallback(void callback(Ref, String?)) → void
Sets the ref registration callback (called by store module).
setTheme(Theme theme, {bool syncToDom = false, String selector = ':root', String prefix = 'lark'}) → void
Sets the current theme.
stylesToCss(Map<String, Style> styles) String
Converts a map of typed styles to a CSS string.
styleToMap(Style props) Map<String, String>
Converts a Style record to a CSS style map.
syncThemeToDom({String selector = ':root', String prefix = 'lark'}) → void
Applies current theme variables to the DOM when running on web.
untrack<T>(T fn()) → T
Runs a function without tracking any dependencies.
useAsync<T>(Future<T> fn(), {bool immediate = false}) AsyncResult<T>
Manage async operation state.
useContentSeo(Map<String, dynamic> metadata, {String? type, String? canonical, String? baseUrl}) → void
Applies SEO metadata from a content item's frontmatter.
useContext<T>() → T
Retrieves a provided value of type T.
useContextOrNull<T>() → T?
Retrieves a provided value of type T, or null if not found.
useContextRef<T>() Ref<T>
Retrieves a provided reactive ref of type T.
useContextRefOrNull<T>() Ref<T>?
Retrieves a provided reactive ref of type T, or null if not found.
useCookie(String name, {CookieOptions options = const CookieOptions()}) CookieResult
Create a reactive ref backed by a cookie.
useDarkMode({String storageKey = _darkModeStorageKey}) DarkModeResult
Create a reactive dark mode controller with persistence.
useDebounce<T>(Ref<T> source, Duration delay) Debounced<T>
Creates a debounced version of source.
useDom() DomResult
Creates browser-safe DOM helpers.
useFetch<T>(String url, {T transform(dynamic json)?, Map<String, String>? headers, bool immediate = true, bool server = true, bool client = true, String? key}) FetchResult<T>
Fetch data from a URL with reactive state tracking.
useForm(Map<String, FieldDef> fields, {List<FormValidator> validators = const [], List<AsyncFormValidator> asyncValidators = const [], AutovalidateMode autovalidateMode = AutovalidateMode.disabled}) FormState
Creates a reactive form.
useHead(List<HeadEntry> entries) → void
Add custom head entries.
useHeadManager() HeadManager
Gets current head manager.
useInfiniteScroll<T>({required Future<PageResult<T>> fetcher(int page), bool immediate = true}) InfiniteScrollResult<T>
Create an infinite scroll data source.
useLazyFetch<T>(String url, {T transform(dynamic json)?, Map<String, String>? headers}) FetchResult<T>
Lazy fetch - only fetches when execute() is called.
useLazyQuery<T>({required QueryKey key, required Future<T> queryFn(), required Ref<bool> enabled, QueryOptions<T>? options}) QueryResult<T>
Create a disabled query that only fetches when enabled.
useLocalStorage(String key, {String? defaultValue}) StorageResult<String?>
Create a reactive ref backed by localStorage.
useLocalStorageJson<T>({required String key, required T defaultValue, required T fromJson(Map<String, dynamic>), required Map<String, dynamic> toJson(T)}) StorageResult<T>
Typed localStorage helper with JSON serialization.
useMeta({String? title, String? description, String? ogTitle, String? ogDescription, String? ogImage, String? ogType, String? ogUrl, String? twitterCard, String? twitterTitle, String? twitterDescription, String? twitterImage, String? canonical, String? robots, String? author, String? themeColor, Map<String, String>? custom}) → void
Sets page meta tags.
useMutation<TData, TVariables, TContext>({required Future<TData> mutationFn(TVariables variables), MutationOptions<TData, TVariables, TContext>? options}) MutationResult<TData, TVariables>
Perform data modifications with optimistic updates and cache invalidation.
usePagination<T>({required Future<PageResult<T>> fetcher(int page), int initialPage = 1, bool immediate = true}) PaginationResult<T>
Create a paginated data source.
useParams() Map<String, String>
Returns route params (reactive via route).
usePolling<T>({required Future<T> fetcher(), required Duration interval, bool immediate = true}) PollingResult<T>
Poll data at regular intervals.
usePost<T>(String url, {T transform(dynamic json)?, Map<String, String>? headers}) HttpMutationResult<T>
Perform a POST request.
usePrevious<T>(Ref<T> source) Previous<T>
Creates a ref that tracks the previous value of source.
useQuery<T>({required QueryKey key, required Future<T> queryFn(), QueryOptions<T>? options}) QueryResult<T>
Fetch and cache server data with automatic state management.
useQueryParams() Map<String, String>
Returns query params (reactive via route).
useRoute() Route
Returns the current route (reactive).
useRouter() Router
Returns the router instance.
useRouteRef() Ref<Route>
Returns the current route as a reactive ref.
useSchemaForm(Map<String, dynamic> schema, {Map<String, NamedValidatorFactory> validatorCatalog = const {}, Map<String, NamedAsyncValidatorFactory> asyncValidatorCatalog = const {}, Map<String, NamedFormatterFactory> formatterCatalog = const {}, Map<String, NamedFormValidatorFactory> formValidatorCatalog = const {}, Map<String, NamedAsyncFormValidatorFactory> asyncFormValidatorCatalog = const {}}) FormState
Build a form from a JSON-like schema.
useSeo({String? title, String? description, String? image, String? url, String? type, String? ogTitle, String? ogDescription, String? ogImage, String? twitterTitle, String? twitterDescription, String? twitterCard, String? canonical, String? robots, String? author, List<String>? keywords, String? themeColor, String? favicon, String? appleTouchIcon, String? manifest}) → void
Unified SEO API with automatic platform fallbacks.
useSessionStorage(String key, {String? defaultValue}) StorageResult<String?>
Create a reactive ref backed by sessionStorage.
useTheme() Theme
Gets the current theme.
useThrottle<T>(Ref<T> source, Duration interval) Debounced<T>
Creates a throttled version of source.
useToggle([bool initial = false]) Toggle
Creates a reactive boolean toggle.

Typedefs

AsyncFormValidator = Future<String?> Function(FormState form)
A form-level async validator for cross-field checks.
AsyncResult<T> = ({Ref<T?> data, Ref<String?> error, Future<void> Function() execute, Ref<bool> loading, void Function() reset})
Result type for useAsync.
AsyncValidator = Future<String?> Function(dynamic value)
An async validation function that returns an error message or null.
CleanupFn = void Function()
Represents a cleanup function returned from an effect.
CookieResult = ({void Function() remove, void Function(String value) set, Ref<String?> value})
Result type for useCookie.
DarkModeResult = ({ReadonlyRef<bool> isDark, ReadonlyRef<String> mode, Ref<ColorScheme> preference, void Function() setDark, void Function() setLight, void Function() setSystem, void Function() toggle})
Result type for useDarkMode.
DomPoint = ({double x, double y})
DomResult = ({bool available, bool Function(String id, {bool preventScroll}) focusById, void Function() lockBodyScroll, bool Function(String selector, {String block, String inline, bool smooth}) scrollIntoView, DomPoint Function() scrollPosition, bool Function(String id, {double offset, bool smooth}) scrollToId, bool Function({double? left, bool smooth, double? top}) scrollToPosition, bool Function({bool smooth}) scrollToTop, void Function() unlockBodyScroll, DomViewport Function() viewport})
Result record for useDom.
DomViewport = ({double height, double width})
EffectFn = CleanupFn? Function()
A function that can optionally return a cleanup function.
EqualityFn<T> = bool Function(T previous, T next)
A function that compares two values for equality.
FetchResult<T> = ({Ref<T?> data, Ref<String?> error, Future<void> Function() execute, Ref<bool> loading, Future<void> Function() refresh})
Result type for useFetch.
FormValidator = String? Function(FormState form)
A form-level validator for cross-field checks.
HttpGet = Future<HttpResponse> Function(String url, {Map<String, String>? headers})
HttpMutationResult<T> = ({Ref<T?> data, Ref<String?> error, Future<void> Function(Object? body) execute, Ref<bool> loading})
Result type for mutations (POST, PUT, DELETE).
HttpPost = Future<HttpResponse> Function(String url, {Object? body, Map<String, String>? headers})
IconClassBuilder = String Function(String prefix, String name)
Resolves the CSS class used to render an icon glyph.
InfiniteScrollResult<T> = ({Ref<String?> error, Ref<bool> hasMore, Ref<bool> initialLoading, Ref<List<T>> items, Future<void> Function() loadMore, Ref<bool> loading, Future<void> Function() refresh})
Result type for useInfiniteScroll.
InputFormatter = String Function(String value)
Transforms raw text input before it is persisted.
MiddlewareFn = void Function(Route to, Route from, NavigationControl next)
A function that guards route navigation.
MutationResult<TData, TVariables> = ({Ref<TData?> data, Ref<String?> error, ReadonlyRef<bool> isError, ReadonlyRef<bool> isIdle, ReadonlyRef<bool> isPending, ReadonlyRef<bool> isSuccess, void Function(TVariables variables) mutate, Future<TData> Function(TVariables variables) mutateAsync, void Function() reset, Ref<QueryStatus> status, Ref<TVariables?> variables})
Result type for useMutation.
NamedAsyncFormValidatorFactory = AsyncFormValidator Function(Map<String, dynamic> config)
Named schema async form validator factory.
NamedAsyncValidatorFactory = AsyncValidator Function(Map<String, dynamic> config)
Named schema async validator factory.
NamedFormatterFactory = ValueFormatter Function(Map<String, dynamic> config)
Named schema formatter factory.
NamedFormValidatorFactory = FormValidator Function(Map<String, dynamic> config)
Named schema form validator factory.
NamedValidatorFactory = Validator Function(Map<String, dynamic> config)
Named schema validator factory.
PaginationResult<T> = ({Ref<String?> error, Future<void> Function(int page) goToPage, Ref<bool> hasMore, Ref<List<T>> items, Future<void> Function() loadMore, Future<void> Function() loadPrevious, Ref<bool> loading, Ref<int> page, Future<void> Function() refresh, Future<void> Function() reset, Ref<int?> total})
Result type for usePagination.
PollingResult<T> = ({Ref<bool> active, Ref<T?> data, Ref<String?> error, Future<void> Function() fetchNow, void Function() start, void Function() stop})
Result type for usePolling.
QueryKey = List<Object?>
A query key uniquely identifies cached data.
QueryResult<T> = ({Ref<T?> data, Ref<DateTime?> dataUpdatedAt, void Function() dispose, Ref<String?> error, Ref<FetchStatus> fetchStatus, ReadonlyRef<bool> isError, ReadonlyRef<bool> isFetching, ReadonlyRef<bool> isLoading, ReadonlyRef<bool> isPending, ReadonlyRef<bool> isStale, ReadonlyRef<bool> isSuccess, Future<void> Function() refetch, Ref<QueryStatus> status})
Result type for useQuery.
Radius = ThemeRadius
Radius token alias.
RebuildCallback = void Function()
Callback for when a component needs to rebuild.
ScrollOffset = ({double x, double y})
Shadow = ThemeShadows
Shadow token alias.
Space = ThemeSpacing
Spacing token alias.
StorageResult<T> = ({void Function() remove, void Function(T value) set, Ref<T> value})
Result type for useLocalStorage.
Typography = ThemeTypography
Typography token alias.
Validator = String? Function(dynamic value)
A validation function that returns an error message or null.
ValueFormatter = dynamic Function(dynamic value)
A value formatter run before validation/storage.
VariantFunction = String Function([Map<String, dynamic>? props])

Exceptions / Errors

EnvError
Environment error.
RouteNotFoundException
Thrown when no route matches the current path.