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

패키지 상세v5.2.0

depend

depend는 Flutter 앱에서 종속성 관리를 단순화하여 위젯 트리 전체에서 서비스를 쉽게 초기화하고 접근할 수 있도록 제공합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.2천
좋아요
10
Pub 점수
160

패키지 설치

flutter pub add depend

패키지 개요

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

depend는 Flutter용 가벼운 종속성 주입 패키지로, 위젯 트리 전체에서 서비스 초기화 및 접근을 간소화합니다. 개발자가 최소한의 반복 코드로 종속성을 등록하고 가져올 수 있게 하여 깔끔한 아키텍처와 테스트 용이성을 촉진합니다. 이 패키지는 Android, iOS, Web, macOS, Windows, Linux를 포함한 모든 주요 플랫폼을 지원하며, 간단한 pub add 명령어로 기존 Flutter 프로젝트에 원활하게 통합할 수 있습니다. 직관적인 API를 통해 코드 유지보수성을 높이고 전역 변수나 컨텍스트 중심 패턴에 대한 의존도를 줄입니다.

사용 사례

  • 여러 화면에 걸쳐 공유 서비스 관리
  • 단위 및 위젯 테스트 간소화
  • 복잡한 공급자 설정 교체
  • 모듈러 앱 아키텍처 활성화
  • 의존성 설정에서 반복 코드 줄이기

주요 기능

  • 간편한 서비스 등록 및 검색
  • 크로스 플랫폼 지원
  • 최소한의 보일러플레이트
  • 내장형 라이프사이클 관리
  • 싱글톤 및 일시적 인스턴스 모두를 지원합니다

적합한 대상

  • 소규모에서 중규모의 Flutter 애플리케이션
  • 간단한 DI 솔루션을 찾는 팀
  • 관심사의 명확한 분리가 필요한 프로젝트
  • 무거운 상태 관리 라이브러리를 피하는 개발자
  • 다중 플랫폼을 대상으로 하는 앱

고려 사항

  • 매우 복잡한 종속성 그래프에는 적합하지 않을 수 있습니다
  • 완전한 DI 프레임워크에 비해 고급 기능이 제한됨
  • 간단한 종속성 요구 사항에 가장 적합
  • 광범위한 런타임 구성이 필요한 앱에는 적합하지 않습니다
  • 대규모 앱을 위한 신중한 계획이 필요합니다

원본 README

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

Logo Frame

depend is a library for dependency management in Flutter applications. It provides a convenient way to initialize and access services and repositories via InheritedWidget.


Features 🚀

  • Dependency Initialization: Prepare all dependencies before the app launches.
  • Global Access: Access dependencies from anywhere in the widget tree.
  • Parent Dependencies Support: Easily create nested or connected dependencies.
  • Ease of Use: Integrate the library into existing code with minimal changes.

Table of Contents


Installation

Add the library to the pubspec.yaml of your project:

dependencies:
  depend: ^latest_version

Install the dependencies:

flutter pub get

Usage Examples

Example 1: Simple Initialization
Step 1: Define the Dependency

Create a class that extends DependencyContainer and initialize your dependencies:

class RootContainer extends DependencyContainer {
  final ApiService apiService;

  RootContainer({required this.apiService});


  void dispose() {
    apiService.dispose();
  }
}
Step 2: Define the DependencyFactory

Create a class that extends DependencyContainer and initialize your dependencies:

class RootDependencyFactory extends DependencyFactory<RootContainer> {
  
  Future<RootContainer> create() async {
    return RootContainer(
      apiService: await ApiService.initialize(),
    );
  }
  
  // or

  RootContainer create() {
     return RootContainer(
        apiService: ApiService.initialize(),
     );
  }
}
Step 3: Use DependencyScope

Wrap your app in a DependencyScope to provide dependencies:

void main() {
  runApp(
    DependencyScope<RootContainer, RootFactory>(
       factory: RootFactory(), 
       placeholder: const Center(child: CircularProgressIndicator()), 
       builder: (BuildContext context) => const MyApp(),
    ),
  );
}
Step 4: Access the Dependency in a Widget

You can now access the dependency using DependencyProvider anywhere in the widget tree:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final apiService = DependencyProvider.of<RootContainer>(context).apiService;

    return FutureBuilder(
      future: apiService.getData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        } else if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }

        return Text('Data: ${snapshot.data}');
      },
    );
  }
}

Example 2: DependencyProvider
final RootContainer dep = await RootFactory().create();

DependencyProvider<RootContainer>(
  dependency: dep,
  builder: () => YourWidget();
  // or
  child: YourWidget()
)

class YourWidget extends StatelessWidget {
  @override
  Widget build(BuildContext) {
    root = DependencyProvider.of<RootContainer>(context);
    ...
  }
}
Example 3: DependencyScope
DependencyScope<RootContainer, RootFactory>(
      factory: RootFactory(),
      builder: (BuildContext context) => Text('Inject'),
      placeholder: Text('Placeholder'),
      errorBuilder: (Object? error) => Text('Error'),
    ),

Example 4: Lazy Initialization

The library provides LazyGet and LazyFutureGet classes for lazy initialization of services. Dependencies are created only when they are first accessed, which improves application startup time.

Using LazyGet for Synchronous Dependencies
class RootContainer extends DependencyContainer {
  // Service will be created only when accessed for the first time
  final LazyGet<ApiService> apiService;
  final LazyGet<DatabaseService> database;
}

class RootDependencyFactory extends DependencyFactory<RootContainer> {
  RootContainer create() {
     return RootContainer(
        apiService: lazyGet(ApiService.initialize),
        database: lazyGet(DatabaseService.initialize),
     );
  }
}

// Usage in widgets
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final container = DependencyProvider.of<RootContainer>(context);
    
    // ApiService is created only at this moment
    final api = container.apiService();
    
    return Text('Service initialized: ${api}'); // Instance: ApiService
  }
}
Using LazyFutureGet for Asynchronous Dependencies
class RootContainer extends DependencyContainer {
  final LazyFutureGet<DatabaseService> database;
      
  final LazyFutureGet<AuthService> authService;
}

class RootDependencyFactory extends DependencyFactory<RootContainer> {
  RootContainer create() {
     return RootContainer(
        apiService: lazyFutureGet(ApiService.initialize),
        database: lazyFutureGet(DatabaseService.initialize),
     );
  }
}

// Usage in widgets
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final container = DependencyProvider.of<RootContainer>(context);
    
    return FutureBuilder<DatabaseService>(
      // Database is initialized only when this widget is built
      future: container.database(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }
        
        return Text('Database ready: ${snapshot.data?.isConnected}');
      },
    );
  }
}

Benefits of Lazy Initialization:

  • Faster App Startup: Dependencies are created only when needed
  • Memory Optimization: Unused services don't consume memory
  • Flexible Initialization: You can control when heavy operations are performed
  • Simple API: Easy to use with both sync and async dependencies

Codecov

Codecov

카테고리

소스 저장소

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

아직 데이터가 없습니다.