flutter-core:flutter-state-management
Comprehensive Flutter state management guidance covering built-in solutions, Provider, BLoC, and Riverpod. Use when working with state management, sharing data between widgets, managing app state, implementing reactive patterns, choosing state solutions, setState, ValueNotifier, ChangeNotifier, InheritedWidget, Provider package, BLoC pattern, Riverpod, state architecture, or comparing state management approaches.
What this skill does
# Flutter State Management
A comprehensive guide to managing state in Flutter applications, from simple built-in solutions to sophisticated state management patterns. This skill helps you understand the state management landscape, choose the right solution for your needs, and implement it effectively.
## Philosophy: Start Simple, Evolve When Needed
Flutter's official philosophy advocates for a pragmatic approach to state management: start with the simplest solution that works, and graduate to more complex patterns only when your application's complexity demands it. This "simple-first" approach prevents over-engineering while ensuring your codebase can scale gracefully.
The key insight is that there is no single "best" state management solution—the right choice depends on your specific requirements, team size, application complexity, and architectural preferences.
## Understanding State Types
Before choosing a state management solution, it's crucial to understand the fundamental distinction between two types of state in Flutter applications.
### Ephemeral State
Ephemeral state (also called UI state or local state) is state that is scoped to a single widget and doesn't need to be shared across the app. This includes:
- Current page in a PageView
- Animation progress or controller state
- Selected tab in a BottomNavigationBar
- Whether a panel is expanded or collapsed
- Current value in a TextField
For ephemeral state, `setState()` is the recommended solution. It's simple, performant, and keeps your code straightforward. Don't reach for complex state management solutions when `setState()` will suffice.
### App State
App state (also called shared state or application state) is state that needs to be shared across multiple widgets or persisted beyond a single screen. This includes:
- User authentication status and profile data
- Shopping cart contents
- User preferences and settings
- Data fetched from APIs
- Application-wide themes or configurations
App state requires a dedicated state management approach to ensure data flows correctly through your widget tree and updates are propagated efficiently.
## The State Management Spectrum
Flutter offers a spectrum of state management solutions, from built-in lightweight options to full-featured architectural patterns:
### Level 1: Built-in Solutions (Start Here)
- **setState()**: For ephemeral widget state
- **ValueNotifier & ValueListenableBuilder**: For simple reactive values
- **ChangeNotifier**: For custom observable objects
- **InheritedWidget**: For propagating data down the tree
- **StreamBuilder & FutureBuilder**: For async data
### Level 2: Lightweight Packages
- **Provider**: Flutter's recommended lightweight solution
- **Riverpod**: Modern, type-safe evolution of Provider
### Level 3: Architectural Patterns
- **BLoC**: Event-driven architecture with strict separation
- **Redux**: Unidirectional data flow with single source of truth
- **MobX**: Observable reactive programming
## Decision Tree: Choosing Your State Management Solution
Use this decision tree to select the appropriate state management approach:
### Question 1: Is this ephemeral or app state?
**If ephemeral (widget-scoped):**
→ Use `setState()` or `ValueNotifier`
→ No additional packages needed
→ **Stop here—you're done!**
**If app state (shared across widgets):**
→ Continue to Question 2
### Question 2: What's your application complexity?
**Simple app (1-3 screens, minimal shared state):**
→ Use `InheritedWidget` or `ValueNotifier` with `InheritedNotifier`
→ Consider Provider if you want a cleaner API
→ **References**: [Built-in State](references/built-in-state.md), [Provider Patterns](references/provider-patterns.md)
**Medium complexity (5-10 screens, moderate shared state):**
→ Use **Provider** for simplicity and community support
→ Use **Riverpod** for type safety and modern features
→ **References**: [Provider Patterns](references/provider-patterns.md), [Riverpod Guide](references/riverpod-guide.md)
**Large/Enterprise app (10+ screens, complex state flows):**
→ Use **Riverpod** for flexibility and compile-time safety
→ Use **BLoC** for strict architecture and enterprise requirements
→ **References**: [BLoC Architecture](references/bloc-architecture.md), [State Comparison](references/state-comparison.md)
### Question 3: Do you have special requirements?
**Need event-driven architecture with audit trails?**
→ Use **BLoC** (excellent for regulated industries)
→ **Reference**: [BLoC Architecture](references/bloc-architecture.md)
**Want compile-time safety and no BuildContext dependency?**
→ Use **Riverpod** (catches errors at compile time)
→ **Reference**: [Riverpod Guide](references/riverpod-guide.md)
**Working with streams extensively?**
→ Use **BLoC** or **StreamBuilder** with built-in solutions
→ **Reference**: [Built-in State](references/built-in-state.md)
**Team prefers simple, familiar patterns?**
→ Use **Provider** (gentle learning curve)
→ **Reference**: [Provider Patterns](references/provider-patterns.md)
## Core Principles for Effective State Management
Regardless of which solution you choose, follow these principles:
### 1. Think Declaratively
Flutter uses a declarative paradigm where **UI = f(state)**. Your UI should be a pure function of your state. Instead of imperatively updating widgets, change the state and let Flutter rebuild the affected widgets.
```dart
// Imperative (wrong approach)
void updateCounter() {
counterText.text = count.toString();
}
// Declarative (Flutter way)
void updateCounter() {
setState(() {
count++;
});
// UI automatically reflects the new state
}
```
### 2. Separate Concerns
Keep your business logic separate from your UI code. State management solutions should handle:
- **Business Logic**: Data transformations, calculations, API calls
- **State**: Current application data
- **UI Logic**: Widget structure and presentation
Your widgets should be thin presentation layers that react to state changes, not contain business logic.
### 3. Minimize Rebuilds
Only rebuild widgets that actually depend on changed state. Use:
- `ValueListenableBuilder` for single values
- `Consumer` or `Selector` in Provider
- `ref.watch()` in Riverpod with granular dependencies
- `BlocBuilder` in BLoC
Avoid rebuilding entire screens when only a small portion needs to update.
### 4. Make State Predictable
State changes should be:
- **Traceable**: Easy to understand what caused a state change
- **Testable**: Business logic can be tested independently
- **Debuggable**: State history can be inspected
### 5. Handle Async Operations Properly
Async state (loading, error, data) is common in real applications. Use:
- `FutureBuilder` and `StreamBuilder` for simple cases
- Provider's `FutureProvider` or Riverpod's `AsyncValue`
- BLoC's event-state pattern with loading states
## Common Patterns and Use Cases
### Pattern 1: Counter App (Learning)
The classic Flutter counter demonstrates basic state management concepts. See how the same app can be implemented with different solutions:
→ **Example**: [Simple State Examples](examples/simple-state.md)
### Pattern 2: Form State (Ephemeral)
Form inputs, validation, and temporary UI state should generally stay local:
- Use `TextEditingController` for text inputs
- Use `setState()` for validation state
- Only elevate to app state if form data needs to be shared
### Pattern 3: Authentication State (App State)
User login status is shared across the entire app:
- Store user data and auth token in app state
- Protect routes based on auth state
- Make auth state available globally
→ **References**: [Provider Patterns](references/provider-patterns.md), [Riverpod Guide](references/riverpod-guide.md)
### Pattern 4: Shopping Cart (Complex App State)
Shopping carts demonstrate complex state with multiple operations:
- Adding/removing items
- Calculating totals
- Persisting across sessions
- Synchronizing with backend
→ **Example**: [ComplexRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.