gbtb16/kiwi

Can I create `kiwi_generator` record for a string?

Closed this issue · 7 comments

Something like

@Register.singleton('localhost', name: 'websiteUrl' )

So that I can easily change it for dev/staging/prod. Often it is useful for other classes created via DIC to have these string parameters. And I cannot come up with any other way than to create a class for each environment and register the class instead.

That is not possible with the genrator. You should register that manually.

KiwiContainer().registerSingleton((container) => 'This is an awesome string', name: 'string_named');

The generator will generate a dependency three. But because your string does not have a constructor or a factory method. it should be added manually.

We register this in our main.dart file. Or call a function that registers this string.

Closing this ticket because it is already implemented and available in the current versions of the library.

@vanlooverenkoen OK, good to know. How do I then resolve the issue where I want the string to be a dependency for something I create via the generator? A assume it is not possible? And I have to also do it the same way in the main.dart file when I register the string?

That would look like this:

import 'package:kiwi/kiwi.dart';

part 'kiwi_generator_example.g.dart';

abstract class Injector {
  @Register.singleton(Service, resolvers: {String: 'my_awesome_string'})
  void configure();
}

class Service {
  Service(String serviceA);
}

void setup(String value) {
  var injector = _$Injector();
  KiwiContainer().registerSingleton((container) => value, name: 'my_awesome_string');
  injector.configure();
}

@vanlooverenkoen thank you for the example. One more question - sorry if too obvious I am new to dart - how do I pass the string value to setup?

your main.dart file

import 'packages:my_app:your_path_to_injector.dart'

void main() {
 setup('your awesome string');

 runApp(MyApp());
}

your injector.dart file

import 'package:kiwi/kiwi.dart';

part 'kiwi_generator_example.g.dart';

abstract class Injector {
  @Register.singleton(Service, resolvers: {String: 'my_awesome_string'})
  void configure();
}

class Service {
  Service(String serviceA);
}

void setup(String value) {
  var injector = _$Injector();
  KiwiContainer().registerSingleton((container) => value, name: 'my_awesome_string');
  injector.configure();
}

One important part to note. is that this will only use the same string. It is best to have multiple main.dart files so threeshaking can be done on your code correctly. If you only include another dart file in main_alpha.dart it will not be shiped with the main_beta.dart app. Take a look at flavors for flutter. Or just use different main.dart files for eacht env/flavor

@vanlooverenkoen Thank you, you have been a big help. Is there a way I can https://www.buymeacoffee.com/ or something? 😄