搜索插件、代码仓与 APP 分类

插件详情v5.2.0

depend

depend 简化了 Flutter 应用中的依赖管理,提供了在组件树中轻松初始化和访问服务的功能。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
1180
喜欢数
10
Pub 分数
160

安装插件

flutter pub add depend

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

depend 是一个轻量级的 Flutter 依赖注入包,可简化在整个 widget 树中服务的初始化和访问。它使开发者能够以最少的样板代码注册和获取依赖项,促进清晰的架构设计并简化测试。该包支持所有主要平台——Android、iOS、Web、macOS、Windows 和 Linux,并可通过简单的 pub add 命令无缝集成到现有的 Flutter 项目中。通过直观的 API,depend 提升了代码的可维护性,减少了对全局变量或上下文密集型模式的依赖。

适合场景

  • 跨多个屏幕管理共享服务
  • 简化单元测试和小部件测试
  • 替换复杂的提供方设置
  • 启用模块化应用架构
  • 减少依赖设置中的样板代码

主要特点

  • 轻松的服务注册与获取
  • 跨平台支持
  • 最小化样板代码
  • 内置生命周期管理
  • 支持单例和瞬态实例

适合对象

  • 中小型Flutter应用
  • 寻求简单依赖注入解决方案的团队
  • 需要清晰关注点分离的项目
  • 开发者避免使用重量级状态管理库
  • 面向多个平台的应用程序

使用建议

  • 可能不适合高度复杂的依赖关系图
  • 与完整的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

所属分类

源码仓库

使用此插件的项目

暂无相关数据。