aloisdeniel/dioc

Flutter best practices

Closed this issue · 2 comments

What would you say the best usage of this in a Flutter widget is (Stateful or Stateless)? Are we hitting the the AppBootsrapperBuilder.instance.instance().create<IServiceType>() within the method body itself or is there a better solution?

One thing similar packages in .NET (and others I think) is constructor injection. Do you think that would be possible (if it isn't already)?

IMHO The simplest and recommended way to give access to your containers would be an InheritedWidget.

class ContainerProvider extends InheritedWidget {
  final Container container;

  ContainerProvider({
    Key key,
    Container container,
    Widget child,
  })  : container = container ?? AppBootstrapper.instance.development(),
        super(key: key, child: child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => true;

  static Container of(BuildContext context) => (context.inheritFromWidgetOfExactType(ContainerProvider) as ContainerProvider).container;
}

You can simply instantiate it at the root of you app tree and access it from wherever in the tree from context!

class MyApp extends StatelessWidget
  @override
  Widget build(BuildContext context) {
    return ContainerProvider(child: MaterialApp( ... ));
  }
}

From a widget instantiated in the tree :

@override
  Widget build(BuildContext context) {
    var container = ContainerProvider.of(context);
    return ...;
  }

I will add a full flutter sample in near future, it is a good idea! 👍

OK that looks good. It would be awesome if we could get constructor injection, but I thought about what this would look like and I really think we need variable length arguments to make it work. This is probably as good as it gets for now. Thanks!