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

插件详情v2.0.0

flutter_simple_dependency_injection

一个超简单的 Flutter 依赖注入实现,行为类似于任何正常的 IOC 容器,且不依赖于 mirrors。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
3880
喜欢数
74
Pub 分数
160

安装插件

flutter pub add flutter_simple_dependency_injection

插件介绍

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

一个轻量级的 Flutter 依赖注入包,提供简单直接、无需镜像的 IOC 容器。它通过允许开发者轻松地在应用程序中注册和解析依赖项,实现关注点的清晰分离。设计简洁且性能优异,避免使用运行时反射,支持树摇优化,适用于生产环境。API 直观易用,可无缝集成到现有的 Flutter 项目中,无复杂性。

适合场景

  • 跨多个小部件管理共享服务
  • 注入仓库和数据源
  • 使用模拟依赖项进行测试
  • 简化复杂对象图的初始化
  • 启用模块化应用架构

主要特点

  • 无镜像依赖解析
  • 简单的注册和检索语法
  • 支持单例和瞬态实例
  • 适用于所有 Flutter 平台
  • 轻量且启动迅速

适合对象

  • 中小型Flutter应用
  • 寻求DI最小化设置的团队
  • 优先考虑性能和树摇的项目
  • 开发人员避免使用复杂的依赖注入框架

使用建议

  • 与完整的DI容器相比,高级功能有限
  • 不支持分层作用域的内置支持
  • 在复杂场景中手动管理生命周期
  • 对于具有复杂依赖关系的大型企业应用程序来说,不是理想选择

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

flutter_simple_dependency_injection

A simple dependency injection plugin for Flutter and Dart.

This implementation does not rely on the dart reflection apis (mirrors) and favours a simple factory based approach. This increases the performance and simplicity of this implementation.

  • Support for multiple injectors (useful for unit testing or code running in isolates)
  • Support for types and named types
  • Support for singletons
  • Support simple values (useful for configuration parameters like api keys or urls)

Any help is appreciated! Comment, suggestions, issues, PR's!

Getting Started

In your flutter or dart project add the dependency:

dependencies:
  ...
  flutter_simple_dependency_injection: any

For help getting started with Flutter, view the online documentation.

Usage example

Import flutter_simple_dependency_injection

import 'package:flutter_simple_dependency_injection/injector.dart';
Injector Configuration

As this injector relies on factories rather than reflection (as mirrors in not available in Flutter) each mapped type needs to provide a factory function. In most cases this can just be a simple new object returned function. In slightly more advanced scenarios where the type to be created relies on other types an injector instances is passed into the factory function to allow the type of be created to get other types it depends on (see below for examples).

import 'package:flutter_simple_dependency_injection/injector.dart';

void main() {
  // it is best to place all injector initialisation work into one or more modules
  // so it can act more like a dependency injector than a service locator.
  // The Injector implements a singleton pattern. You can get a singleton injector instance
  // just by calling Injector().
  final injector = ModuleContainer().initialise(Injector());

  // NOTE: it is best to architect your code so that you never need to
  // interact with the injector itself.  Make this framework act like a dependency injector
  // by having dependencies injected into objects in their constructors.  That way you avoid
  // any tight coupling with the injector itself.

  // Basic usage, however this kind of tight couple and direct interaction with the injector
  // should be limited.  Instead prefer dependencies injection.

  // simple dependency retrieval and method call
  injector.get<SomeService>().doSomething();

  // get an instance of each of the same mapped types
  final instances = injector.getAll<SomeType>();
  print(instances.length); // prints '3'

  // passing in additional arguments when getting an instance
  final instance =
      injector.get<SomeOtherType>(additionalParameters: {"id": "some-id"});
  print(instance.id); // prints 'some-id'
}

class ModuleContainer {
  Injector initialise(Injector injector) {
    injector.map<Logger>((i) => Logger(), isSingleton: true);
    injector.map<String>((i) => "https://api.com/", key: "apiUrl");
    injector.map<SomeService>(
        (i) => SomeService(i.get<Logger>(), i.get<String>(key: "apiUrl")));

    // note that you can configure mapping in a fluent programming style too
    injector.map<SomeType>((injector) => SomeType("0"))
            ..map<SomeType>((injector) => SomeType("1"), key: "One")
            ..map<SomeType>((injector) => SomeType("2"), key: "Two");

    injector.mapWithParams<SomeOtherType>((i, p) => SomeOtherType(p["id"]));

    return injector;
  }
}

class Logger {
  void log(String message) => print(message);
}

class SomeService {
  final Logger _logger;
  final String _apiUrl;

  SomeService(this._logger, this._apiUrl);

  void doSomething() {
    _logger.log("Doing something with the api at '$_apiUrl'");
  }
}

class SomeType {
  final String id;
  SomeType(this.id);
}

class SomeOtherType {
  final String id;
  SomeOtherType(this.id);
}

Remove mappings

You can remove a mapped a factory/instance at any time:

  injector.removeMapping<SomeType>();

  injector.removeMapping<SomeType>(key: 'some_key');

  injector.removeAllMappings<SomeType>();
Multiple Injectors

The Injector class has a factory constructor that by default returns the default singleton instance of the injector. In most cases this will be enough. However, you can pass a name into this factory constructor to return another isolated injector that is independent from the default injector. Passing in a new injector name will create the injector if it has not be retrieved before.

  final defaultInjector = Injector();
  final isolatedInjector = Injector("Isolated");

To destroy an injector instance call its dispose method. The particular instance of the injector with all mappings will be removed.

  Injector().dispose();
  Injector("Isolated").dispose();

所属分类

源码仓库

使用此插件的项目