Dart
Getting Started with Dart
This tutorial lets you write a Dart application and use Koin inject and retrieve your components.
Setup
First, check that the koin
package dependency is added like below:
Package | Pub |
---|---|
koin |
The application
In our small app we need to have 2 components:
- HelloMessageData - hold data
- HelloService - use and display data from HelloMessageData
- HelloApplication - retrieve and use HelloService
Data holder
Let's create a HelloMessageData
data class to hold our data:
Service
Let's create a service to display our data from HelloMessageData
. Let's write HelloServiceImpl
class and its interface HelloService
:
The application class
To run our HelloService
component, we need to create a runtime component. Let's write a HelloApplication
class and tag it with KoinComponent
interface. This will later allows us to use the get()
functions to retrieve our component:
Declaring dependencies
Now, let's assemble HelloMessageData
with HelloService
, with a Koin module:
We declare each component as single
, as singleton instances.
single((s) => HelloMessageData())
: declare a singleton ofHelloMessageData
instancesingle<HelloService>((s) => HelloServiceImpl(s.get()))
: BuildHelloServiceImpl
with injected instance ofHelloMessageData
, declared as singleton ofHelloService
.
That's it!
Just start our app from a main
function: