패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.2.1

scoped_deps

dart:async의 Zones를 기반으로 한 스코프 종속성 관리를 위한 간단한 Dart 라이브러리입니다.

AndroidiOSLinuxmacOSWebWindows
30일 다운로드
11.8만
좋아요
9
Pub 점수
160

패키지 설치

flutter pub add scoped_deps

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Scoped_deps는 dart:async의 Zones를 사용하여 범위 지정된 종속성을 관리하는 가벼운 Dart 라이브러리입니다. 개발자가 앱의 특정 부분에서 격리된 종속성 컨텍스트를 만들 수 있게 해주며, 종속성이 의도한 위치에서만 접근 가능하도록 보장합니다. 이는 전역 상태를 피함으로써 더 깔끔한 코드 구조와 더 나은 테스트 가능성에 기여합니다. 이 라이브러리는 모든 플랫폼에서 Flutter 앱과 원활하게 통합되며, 스코프 영역 내에서 종속성 등록 및 검색을 위한 간단한 API를 제공합니다.

사용 사례

  • UI 전용 종속성 관리
  • 개별 컴포넌트 테스트
  • 전역 상태 오염 피하기
  • 모듈형 애플리케이션 섹션 만들기
  • 대규모 앱에서 종속성 주입을 단순화하기

주요 기능

  • 영역 기반 종속성 스코핑
  • 최소 API 표면
  • 크로스 플랫폼 지원
  • Flutter와의 간편한 통합
  • 런타임 오버헤드 없음

적합한 대상

  • 경량 DI를 찾는 Flutter 개발자
  • 모듈식 아키텍처를 가진 앱
  • 명확한 종속성 경계가 필요한 팀
  • 테스트 주도 개발 워크플로우
  • 무거운 프레임워크를 피하는 프로젝트

고려 사항

  • 복잡한 종속성 그래프에 적합하지 않습니다
  • Zones에 대한 이해가 필요합니다
  • 성숙한 라이브러리에 비해 문서가 제한적
  • 작은부터 중간 규모의 앱에 적합
  • 기존 종속성 패턴을 재구조화해야 할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Scoped Deps

A simple dependency injection library built on Zones.

read resolves bindings from an internal registration table that tracks each [Zone] established by this library, so it is not fooled by [Zone]'s inherited [] behavior (which can copy a parent's [ScopedRef] into a middle zone and mask a child's override). For subprocess or other IO that may resume outside that zone, combine with [Zone.bindUnaryCallback] (or related APIs) when registering native callbacks.

Quick Start

import 'package:scoped_deps/scoped_deps.dart';

final value = create(() => 42);

void main() {
  runScoped(scopeA, values: {value});
}

void scopeA() {
  print(read(value)); // 42
  runScoped(scopeB, values: {value.overrideWith(() => 0)});
}

void scopeB() {
  print(read(value)); // 0
}

Recommended: hide read behind a getter

Calling read(valueProvider) at every call site works, but it spreads ScopedRefs through code that shouldn't need to know they exist. Pair each ScopedRef with a top-level getter instead, and let the rest of the app read it like an ordinary variable:

final valueProvider = create(() => 42);
int get value => read(valueProvider);
void main() {
  runScoped(() {
    print(value); // 42
  }, values: {valueProvider});
}

Anything that reads value — no matter how deeply nested — resolves against whichever scope is active when it runs. Callers never import ScopedRef or call read directly, which also makes the pattern straightforward to test (see Testing below).

API

  • create(() => value) — declare a ScopedRef<T>.
  • read(ref, {orElse}) — resolve ref in the current scope; throws a StateError (or calls orElse) if no scope provides it.
  • isRegistered(ref) — check whether ref is bound in the current scope, without the StateError/orElse path.
  • runScoped(body, {values}) — run body in a scope that provides values.
  • runMergedScoped(body, {override, includeIfAbsent}) — run body in a scope forked from the current one. override replaces the current binding for those refs; includeIfAbsent adds a binding only for refs the current scope chain doesn't already define.
  • runMergedScopedFuture(body, {override, includeIfAbsent, zoneSpecification}) — like runMergedScoped, but requires an explicitly async body and accepts an optional zoneSpecification (e.g. to intercept print). override / includeIfAbsent survive await in runMergedScoped too — reach for this variant when you want the stricter async signature or need zoneSpecification, not because bindings would otherwise be lost.
  • runScopedGuarded(body, {onError, values}) — like runScoped, but uncaught errors are routed to onError instead of thrown.
  • ref.overrideWith(() => other) — a ref with the same identity as ref but a different value factory, used to substitute a value for a nested scope (or in a test).

Testing

Bindings live on the Zone, so they don't exist until something establishes a scope — code under test has to run inside a runScoped / runMergedScoped call that provides whatever it reads. A setUp can't do this on its own: it runs to completion before the test body starts, so any scope it forks is already gone by the time your test executes. Wrap the test body itself:

final valueProvider = create(() => 42);
int get value => read(valueProvider);

int doubleValue() => value * 2;

test('doubleValue uses the overridden value', () {
  runScoped(() {
    expect(doubleValue(), equals(20));
  }, values: {valueProvider.overrideWith(() => 10)});
});

The override applies no matter how deep the call chain is — doubleValue() never has to know it's under test. The same works for async code under test; the override stays bound across every await:

Future<int> asyncDoubleValue() async {
  await Future<void>.delayed(Duration.zero);
  return value * 2;
}

test('asyncDoubleValue uses the overridden value', () async {
  await runScoped(() async {
    expect(await asyncDoubleValue(), equals(20));
  }, values: {valueProvider.overrideWith(() => 10)});
});

Reach for runMergedScopedFuture instead when a test also needs a zoneSpecification — for example, to capture print output for the duration of the test rather than letting it hit the console.

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.

순위