stark 0.0.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 56

stark #

What is Stark? #

A pragmatic lightweight dependency injection framework for Dart developers.

Some info #

This project is based on koin

This implementation does not rely on the dart reflection apis (mirrors) and favours a simple factory based approach. This increases the performance and simplicity of this implementation.

Any help is appreciated! Comment, suggestions, issues, PR's!

Getting Started #

In your flutter or dart project add the dependency:

dependencies:
  ...
  stark: 0.0.2

Usage example #

Import stark

import 'package:stark/stark.dart';

Modules definition #

import 'package:stark/stark.dart';

final appModule = {
    single((i) => Api()), 
    single<Repository>((i) => MyRepository(i.get())),
    factory((i) => UseCase(i.get())), 
    factoryWithParams((i, p) => ViewModel(i.get(), p["dynamicParam"])),
};

Initialize Stark #


//You can pass a list with many modules
Stark.init([
  appModule,
  domainModule,
  presentationModule
]);

Getting a inject instance #

class LoginScreen extends StatefulWidget{
  @override
  State<StatefulWidget> createState()  => LoginScreenState();
}

class LoginScreenState extends State<LoginScreen>{

  final _loginViewModel = Stark.get<LoginViewModel>();

  @override
  Widget build(BuildContext context) {
   
    return  Container(
        ...
    );
  }
}

Singleton definition #

import 'package:stark/stark.dart';

final myModule = {
    single((i) => Api(i.get())), 
};

Factory definition #

import 'package:stark/stark.dart';

final myModule = {
    factory((i) => UseCase()), 
};

Named injections #

import 'package:stark/stark.dart';

final myModule = {
    single((i) => Api(), named: "DEFAULT"), 
    single((i) => Api(), named: "EXTERNAL"), 
};


// to get named injections
Stark.get<Api>(named: "DEFAULT");

Dynamic params #

import 'package:stark/stark.dart';

final myModule = {
    singleWithParams((i,p) => Api(p["token"])), 
    factoryWithParams((i,p) => MyPresenter(p["view"])), 
};


// to get with dynamic params
Stark.get<Api>(params: { "token" : "Bearer asdasdad"})
Stark.get<MyPresenter>(params: { "view" : this})

Scoped injections #

  • When you define a scope for an injection, you can dipose it by associating it with a Scope Widget or manually using Stark.disposeScope (name)
  • If your injected class implements Disposable interface the dispose method is called before discard instance.
import 'package:stark/stark.dart';

final myModule = {
    single((i) => LoginViewModel(i.get<>()), scope: "Login" ), 
};

...
 
//Using Scope widget the "Login" scope is disposed when widget is disposed
@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Scope(  
      name: "Login",
      child: LoginWidgetScreen()
    )
  );
}

class LoginViewModel implements Disposable {
    @override
    dispose(){
      //this method is called when the "Login" scope is diposed, use to dispose your RX Subjects or Streams
    }
}


//Or You can dispose manually using:
Stark.disposeScope("Login");

License #

Copyright 2020 The Stark Authors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

[0.0.1] - First version #

[0.0.2] - Scoped Dependencies #

  • When you define a scope for an injection, you can dipose it by associating it with a Scope Widget or manually using Stark.disposeScope (name)
  • If your injected class implements Disposable interface the dispose method is called before discard instance.

final myModule ={
  single((i) => Api(),scoped: "MyScope"),
};

Scope(
  name: "MyScope",
  child: MyWidget() // widget to associate the scope
) // Use scope with a normal Widget.


//To dispose a scope manually uses:
Stark.diposeScope("MyScope");

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:stark/stark.dart';

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

class Api{
  Future<String> getText()async{
    return "Api return";
  }
}

abstract class Repository{
  Future<String> getText();
}

class MyRepository  implements Repository{

  final Api _api;

  MyRepository(this._api);

  @override
  Future<String> getText() async {
     final apiResult = await _api.getText();
     return "$apiResult + Respository data";
  }
}


class ViewModel{

  final Repository _repository;
  final String _dynamicParams;

  ViewModel(this._repository, this._dynamicParams);

  Future<String> getText() async {
    final repositoryResult = await _repository.getText();
    return "$repositoryResult +  ViewModle data and  $_dynamicParams";
  }
}


class MyApp extends StatelessWidget {

  Set<Bind> module = {
    single((i) => Api(),scope: ""),
    single<Repository>((i) => MyRepository(i.get())),
    singleWithParams((i, p) => ViewModel(i.get(), p["name"])),
  };

  @override
  Widget build(BuildContext context) {
    Stark.init([module]);
    return MaterialApp(
      title: 'Stark Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Stark Example'),
    );
  }
}


class MyHomePage extends StatefulWidget {

  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final viewModel = Stark.get<ViewModel>(params: {"name": "Custom dynamic param"});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: FutureBuilder(
          future: viewModel.getText(),
          builder: (context, snapshot){
            if(snapshot.hasData){
              return Text(snapshot.data);
            }
              return CircularProgressIndicator();
          }
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  stark: ^0.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:stark/stark.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
15
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
56
Learn more about scoring.

We analyzed this package on Jul 10, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • stark that is a package requiring null.

Health issues and suggestions

Document public APIs. (-0.06 points)

30 out of 31 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Format lib/src/disposable.dart.

Run flutter format to format lib/src/disposable.dart.

Format lib/src/injector.dart.

Run flutter format to format lib/src/injector.dart.

Format lib/src/instance_factory.dart.

Run flutter format to format lib/src/instance_factory.dart.

Fix additional 5 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/module.dart (Run flutter format to format lib/src/module.dart.)
  • lib/src/scope.dart (Run flutter format to format lib/src/scope.dart.)
  • lib/src/stark.dart (Run flutter format to format lib/src/stark.dart.)
  • lib/src/stark_exception.dart (Run flutter format to format lib/src/stark_exception.dart.)
  • lib/stark.dart (Run flutter format to format lib/stark.dart.)

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.2
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test