“Dependency Injection” in Flutter with InheritedWidget

Gonçalo Palma
Flutter Community
Published in
7 min readApr 12, 2019

--

Photo by Garett Mizunaka on Unsplash

Flutter and Dart gives us a lot of liberty. So much that we can write an entire app in just one file, combining UI, business logic and API calls in a tremendous dart file. However, we tend not to do this as software developers, for many reasons. For starters, it’ll be a mess to test the code, it’ll be difficult to implement new features or correct bugs while traversing through thousands of lines of code and it will also could prove troublesome for future new elements in the project, since a monolithic file of code can be daunting.

That’s why we tend to decouple the code of our app in several classes: network, models, bloc and widgets, etc… However, since these classes depend on each other, we start to notice a couple of issues:

  • Where should we initialise each class?
  • Where and how should we access them?

Let’s look at the following example:

If our HomePageWidget needs to access HomeBloc, it will have to know how to initialise classes HttpClient, NetworkEndpointsA and NetworkEndpointsB. But…

--

--

Gonçalo Palma
Flutter Community

Author, Flutter Lead Developer @Pvotal Tech. Organizer, Google Developer Expert for Flutter and Dart, Lead Flutter Developer. 🌍 https://gpalma.pt/