Flutter依赖注入插件inject_creator的使用
Flutter依赖注入插件inject_creator的使用
inject_creator 是一个方便的代码生成器,用于简化 get_it 的依赖注入。它支持多种功能,包括单例模式、懒加载单例、可变对象、别名、工厂方法、构造后处理、销毁方法以及组件支持。
特性
- 单例模式 (
Singleton) - 懒加载单例 (
LazySingleton) - 可变对象 (
Mutable) - 别名 (
Alias) - 工厂方法 (
FactoryMethod) - 构造后处理 (
PostConstruct) - 销毁方法 (
DisposeMethod) - 组件支持 (
Component) 
开始使用
安装依赖
在 pubspec.yaml 文件中添加以下依赖:
dependencies:
  get_it: ^6.0.0
  inject_creator: any
dev_dependencies:
  build_runner: ^2.0.0
  inject_creator_generator: any
运行以下命令以安装依赖:
flutter pub get
初始化注入器
在应用程序入口处初始化注入器。你可以选择同步或异步初始化。
同步初始化
import 'main.dep.dart';
[@EnableInjector](/user/EnableInjector)(allReady: true)
void main() {
  configDependencies(); // 同步初始化
  runApp(const MyApp());
}
异步初始化
import 'main.dep.dart';
[@EnableInjector](/user/EnableInjector)(allReady: false)
void main() async {
  await initDependencies(); // 异步初始化
  runApp(const MyApp());
}
在初始化完成后,可以通过 getXxxx() 方法获取实例:
getXxxx(); // 获取同步初始化的实例
await getSharedPreferences(); // 获取异步初始化的实例
生成注入代码
运行以下命令以生成注入代码:
flutter pub run build_runner build
示例代码
以下是一个完整的示例,展示如何使用 inject_creator。
单例模式 (Singleton)
@Singleton()
class LoginService {}
@Singleton(tag: 'customNameService')
class CustomNameService {}
abstract class AbstractService {}
@Singleton(tag: 'default', as: AbstractService)
class AbstractServiceImpl extends AbstractService {}
懒加载单例 (LazySingleton)
@LazySingleton()
class LazySingletonService {}
可变对象 (Mutable)
@Mutable()
class NoSingletonService {}
构造后处理 (PostConstruct)
@Singleton()
class LoginService {
  @PostConstruct()
  void init() {
    print('PostConstruct init'); // 构造后执行的逻辑
  }
}
工厂方法 (FactoryMethod)
@LazySingleton(tag: 'asyncService')
class AsyncService {
  @FactoryMethod()
  static Future<AsyncService> withDependencies(LoginService loginService) {
    return Future.value(AsyncService()); // 返回异步实例
  }
}
销毁方法 (DisposeMethod)
@LazySingleton()
class DbService {
  @DisposeMethod()
  void dispose() {
    print('Disposing DbService'); // 销毁时执行的逻辑
  }
}
别名 (Alias)
@LazySingleton()
class FactoryMethodService {
  @FactoryMethod()
  static Future<FactoryMethodService> withDependencies({
    @Alias('asyncService') required Future<AsyncService> asyncService,
    @Alias.by(SimpleAbstractService) required AbstractService abstractService,
  }) {
    return Future(() => FactoryMethodService());
  }
}
第三方库支持 (Component)
@Component()
class VendorComponent {
  @LazySingleton(tag: 'defaultSharedPreferences')
  Future<SharedPreferences> get sharedPreferences => SharedPreferences.getInstance();
  @DisposeMethod()
  void dispose() {
    sharedPreferences.then((value) => value.clear()); // 清理共享偏好设置
  }
}
完整示例
以下是一个完整的 Flutter 应用程序示例,展示了如何使用 inject_creator。
main.dart
import 'package:flutter/material.dart';
import 'package:inject_creator/inject_creator.dart';
import 'main.dep.dart'; // 注入代码生成文件
[@EnableInjector](/user/EnableInjector)(allReady: true) // 同步初始化
void main() {
  configDependencies();
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('You have pushed the button this many times:'),
            Text('$_counter', style: Theme.of(context).textTheme.headline4),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
更多关于Flutter依赖注入插件inject_creator的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter依赖注入插件inject_creator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
inject_creator 是一个用于 Flutter 的依赖注入(DI)插件,它可以帮助你更轻松地管理和注入依赖项。以下是如何使用 inject_creator 的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml 文件中添加 inject_creator 依赖:
dependencies:
  flutter:
    sdk: flutter
  inject_creator: ^1.0.0  # 请使用最新版本
然后运行 flutter pub get 来安装依赖。
2. 创建依赖注入容器
你可以通过继承 InjectCreator 类来创建一个依赖注入容器。在这个容器中,你可以注册和获取依赖项。
import 'package:inject_creator/inject_creator.dart';
class MyInjector extends InjectCreator {
  [@override](/user/override)
  void dependencies() {
    // 注册依赖项
    registerSingleton<MyService>(() => MyServiceImpl());
    registerFactory<MyRepository>(() => MyRepositoryImpl());
  }
}
3. 注册依赖项
在 dependencies 方法中,你可以使用 registerSingleton 和 registerFactory 方法来注册依赖项。
registerSingleton<T>:注册一个单例依赖项,整个应用程序生命周期内只会创建一个实例。registerFactory<T>:注册一个工厂依赖项,每次调用时都会创建一个新的实例。
4. 获取依赖项
你可以通过 get<T>() 方法来获取已注册的依赖项。
void main() {
  final injector = MyInjector();
  injector.init();  // 初始化依赖注入容器
  final myService = injector.get<MyService>();
  myService.doSomething();
  final myRepository = injector.get<MyRepository>();
  myRepository.fetchData();
}
5. 使用依赖注入
你可以在应用程序的任何地方使用 InjectCreator 来获取依赖项。例如,在 Widget 中:
class MyHomePage extends StatelessWidget {
  final MyService myService = InjectCreator.instance.get<MyService>();
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Inject Creator Example'),
      ),
      body: Center(
        child: Text('Service: ${myService.doSomething()}'),
      ),
    );
  }
}
6. 初始化依赖注入容器
在应用程序的入口点(如 main 函数)中,初始化依赖注入容器:
void main() {
  final injector = MyInjector();
  injector.init();
  runApp(MyApp());
}
7. 清理依赖项(可选)
如果你的依赖项需要清理,可以在 InjectCreator 子类中重写 dispose 方法:
class MyInjector extends InjectCreator {
  [@override](/user/override)
  void dependencies() {
    registerSingleton<MyService>(() => MyServiceImpl());
  }
  [@override](/user/override)
  void dispose() {
    // 清理资源
    get<MyService>().dispose();
  }
}
        
      
            
            
            
