Essentials

ShardLocator

Register and resolve singletons without a separate package—API clients, repositories, and config in one place.

Overview

ShardLocator lets you register and resolve singletons (API clients, repositories, config) without adding another package. Register in main() and resolve anywhere with get<T>(). No GetIt, no heavy framework—just a small API built into Shard.

Use it for:

  • API clients – One HTTP client for the app
  • Repositories – Data layer accessed from shards or widgets
  • Config – App-wide settings or feature flags

registerSingleton

Register an existing instance. Every call to get<T>() returns this same instance.

void main() {
  ShardLocator.registerSingleton<ApiClient>(ApiClient());
  runApp(MyApp());
}

// Elsewhere
final api = ShardLocator.get<ApiClient>();

registerLazySingleton

Register a factory that runs once on the first get<T>(). The result is cached; later calls return the same instance. Use this when the type depends on other registered singletons.

void main() {
  ShardLocator.registerSingleton<ApiClient>(ApiClient());
  ShardLocator.registerLazySingleton<Repository>(
    () => Repository(ShardLocator.get<ApiClient>()),
  );
  runApp(MyApp());
}

get

Resolve the registered singleton for type T. Throws StateError if nothing is registered for that type. For lazy singletons, the factory is run on the first call.

final repo = ShardLocator.get<Repository>();

isRegistered

Check whether a singleton (eager or lazy) is registered for type T. Useful for conditional registration or tests.

if (!ShardLocator.isRegistered<ApiClient>()) {
  ShardLocator.registerSingleton<ApiClient>(ApiClient());
}

reset

Clear all registrations. Call this in test setUp so each test starts with a clean locator.

setUp(() => ShardLocator.reset());

Next Steps

Next: Future Shard for async state from a Future. See also: Stream Shard, Examples.