Examples

Best Practices

Short guidelines for using Shard effectively.

Where to put ShardProvider

Place ShardProvider (or MultiShardProvider) high enough so that every widget that needs to read the shard is a descendant. Avoid putting it at the root if only a few screens need it—prefer the route or screen that uses the shard so the shard is disposed when the user leaves.

Prefer ShardSelector over ShardBuilder

When you only need a part of the state, use ShardSelector so the widget rebuilds only when that part changes. This reduces unnecessary rebuilds and keeps the UI responsive.

When to call refresh()

  • FutureShard: Call refresh() when the user explicitly requests fresh data (e.g. pull-to-refresh). Use refresh(invalidateCache: false) if you want to keep showing cached data while fetching in the background.
  • StreamShard: Call refresh() to cancel the current stream subscription and re-subscribe (e.g. after changing a filter).

Commands vs reads

Use a CommandShard for explicit actions the user triggers—submit, create, update, delete. Use a FutureShard for reads that should run automatically (e.g. fetch on screen open). Commands give you an explicit execute(arg) plus a built-in double-submit guard; reads just run.

Derive, don't recompute

When a value is derived from other shards (totals, filtered lists, formatted strings), put it in a ComputedShard instead of recomputing it inside every widget build. The derived value is cached and only recomputed when its inputs change.

Side effects belong in listeners

Navigate, show snackbars, or open dialogs from a ShardListener, never from a builder. Builders can run many times and may be skipped by the framework; a ShardListener fires once per matching state change, which is exactly what a side effect needs.

Test with the fakes

Reach for the test helpers in package:shard/shard_test.dart: ShardTester to drive a shard through states, plus FakeStateStorage, FakeCacheService, and MockShardObserver to stub out persistence, caching, and observation. See Testing.

Clear on logout, version your schema

When you wipe user data (e.g. on logout), call clearPersistence() and reset in-memory state with an emit(...)clearPersistence() only removes the stored slice. When the persisted model changes shape, bump version and provide a migrate so old saved data still loads. See Persistent Shard.

One clear next step

After reading a page, prefer moving to a single "Next" step instead of jumping to many links. Follow the docs in order: Getting Started → Essentials → All Shards → Examples.

Next Steps

You've reached the end of the Examples section. Review the Todo App or Infinite Scroll for full examples, or head back to Core Concepts to deepen your understanding.