gbtb16 / kiwi

A simple compile-time dependency injection library for Dart and Flutter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Generate custom Stateless widget and State

opened this issue · comments

Don't know if other people doing it or not, but to minimize usage of service locator I often find myself adding custom classes that fake method injection. Something like:

abstract class StatelessWidgetInjected<TDependency> extends StatelessWidget {
  TDependency _resolve() => KiwiContainer().resolve<TDependency>();

  @override
  Widget build(BuildContext context) {
    return buildInjected(context, _resolve());
  }

  Widget buildInjected(BuildContext context, TDependency dependency);
}

abstract class StateInjectedInitAndBuild<TWidget extends StatefulWidget, TDependency>
    extends State<TWidget> {
  TDependency _resolve() => KiwiContainer().resolve<TDependency>();

  @override
  void initState() {
    super.initState();
    initStateInjected(_resolve());
  }

  @override
  Widget build(BuildContext context) {
    return buildInjected(context, _resolve());
  }

  void initStateInjected(TDependency dependency);

  Widget buildInjected(BuildContext context, TDependency dependency);
}

So that you can simply use

class MyWidget extends StatelessWidgetInjected<IServiceA> {
  @override
  Widget buildInjected(BuildContext context, IServiceA dependency) {
    // use dependency
    // ...
  }
}

It's just an example of course.

Maybe you can add something like this to the generated output, so that the option to use it is there right out of the box.

Kiwi is a dart package, not a package specifically created for Flutter. This is something that could be added to a third-party package.

You could maybe create a couple of these widgets and use generics to get the correct classes for the KiwiContainer.