Home > Blockchain >  Flutter - why dependency injection?
Flutter - why dependency injection?

Time:10-01

I am developing flutter for about 2 years and I have work with various design patterns. but I haven't used dependency injection. I can't understand what's the point of using the dependency injection? could you please give me an example?

Thanks in Advance

CodePudding user response:

Have you ever created a class (or function) which depends on another object? If so, you have used dependency injection.

class HomeScreen extends StatelessWidget {
  // Dependency
  final String title;

  const HomeScreen({required this.title});

  @override
  Widget build(BuildContext context) {
    return Text(title);
  }
}

void main() {
  runApp(
    HomeScreen(title: 'My title'), // Injection
  );
}

It has nothing to do with Flutter, nothing to do with any Framework for that matter:

void printTitle({
  required String title, // Dependency
}) {
  print(title);
}

void main() {
  // Injection
  printTitle(title: 'My title');
}

Is that all there is to it? Well... Yes. People make a fuss about using complex method to basically achieve just that.

Now, using packages to achieve dependencies injection often brings several features which can be interesting depending on your use cases, some of them being:

  • Lazy loading
  • State sharing
  • Easy access to the state
  • Disposable resource

Those are topic in and of themselves but if you have been using flutter for 2 years you likely know what they mean. Hope this helps, this is far from being exhaustive but is a good introduction I think ;)

CodePudding user response:

Personally I hate the term "dependency injection". I'd just call it "dependency parameterization" (if you need to call it anything at all).

Regardless of what you call it, it's important for testing components of your class hierarchy separately and in a controlled manner. For example, you might have a class that depends on making HTTP requests. You wouldn't want to actually perform network requests in a unit test since there could be network problems, the HTTP server might be temporarily unavailable, etc. Instead of making your class directly depend on an HttpClient, you could make the caller supply that dependency. That way in a unit test, you can make callers supply a fake HttpClient that behaves deterministically.

Usually it's a natural result of making your code testable. It's quite likely you're already doing that without the fancy jargon. There are some "dependency injection" frameworks that try to make the process of plumbing arguments through multiple layers easier, but do whatever works for you.

  • Related