In this article, we are going to look at how we can implement dependency injection in flutter and various methods by which we can implement dependency injection in a flutter.

First of all, what is dependency injection and why we need to use this concept in our project

Dependency injection is the way by which we can implement IOC(Inversion of Control) in which we are creating dependent objects outside of the class and pass that object through different methods of DI.

Now, we are going to understand different methods to implement DI, we have many ways by which we can implement DI in flutterð.

  1. Passing object trough constructor argument
  2. Inherited widget
  3. IOC package
  4. get_it package

Now let’s start with the first and most simpler way to implement DI by Passing object trough constructor argument. in this, we can create an object of the dependent class in the parent level and pass the object through the constructor of the child in which we are going to use that object.

let’s implement one example of this and understand more about this type of dI. so let’s assume we have one ApiService() call in which we have written our all API related calls, now we need ApiService class object in our HomeScreen.

void main() => runApp(MyApp());

	class MyApp extends StatefulWidget {
	  @override
	  _MyAppState createState() => _MyAppState();
	}

	class _MyAppState extends State<MyApp> {
	  @override
	  ApiService apiService= ApiService()
	  Widget build(BuildContext context) {
	    return HomeScreen(service:apiService);
	  }
	}

And in HomeScreen we have take object in the constructor, like this example

#solid #flutter #dart

Dependency Injection for flutter
2.90 GEEK