Flutter’s Dependency Injection?

Greg Perry
Flutter Community
Published in
15 min readJun 26, 2020

--

Another more intuitive yet subtle approach to DI in Flutter

A quick search of the phrase, “Dependency Injection” in Flutter Community will give you a list of articles. All are very informative and offer libraries and ‘service locators’ to implement Dependency Injection. This article will offer an alternative to implementing code and or annotations to supply DI.

Now, I’m not picking on Marc Guilera in particular and his article, Dependency Injection In Flutter. It’s a good read. I only took issue with the two bullet points in his article now displayed below as they pertained to the example code displayed further below.

  • It’s impossible to mock the wheel to test the Car class in isolation.
  • If you had a SteelWheel and a PlasticWheel it would not be possible to interchange them without changing the consumer.
class Car {  
private Wheel wheel = Wheel()

drive() {
wheel.spin()
}
}
Dependency Injection in Flutter

It involved dependency injecting of different types of ‘Wheels’ into the consumer class, Car. He noted the one solution is a parameter of type, Wheel, in the constructor of the consumer class allowing you to create a particular type of Wheel ‘outside’ the class, Car. In the end, he offers his own library, dependencis_flutter, as another solution to overcome these…

--

--