How the GetIt service locator package works in Dart

Suragch
Flutter Community
Published in
9 min readJul 12, 2023

--

Unveiling the magic

magic

The GetIt package provides a convenient way to access app services and state management classes from anywhere within your app. This functionality is known as a service locator, which is often compared to dependency injection, another common way to decouple dependencies in your app.

The idea of dependency injection is easy enough (just pass your dependencies in as constructor arguments), but in a Flutter project I never really understood where to create those service objects in the first place. I like GetIt because it’s easy to use. You define all of your services in one file and then get them from anywhere in your app with a single line of code.

I started writing about GetIt a long time ago. Probably the earliest article was Creating services to do the work in your Flutter app. I didn’t understand how GetIt worked under the hood, though. It was a magic black box. Even in Flutter state management for minimalists, where I purposefully avoided all third-party state management packages, I still used GetIt. I wondered, though, do I really need GetIt? Could I just write the code myself? How does it even work? I thought about that even more after writing Thoughts on using third-party packages (or not).

--

--