Dart dependency injection of a class with parameters

2,659

Solution 1

You just pass the argument you want to MyClass(). You don’t have to do it inside setUpLocator(). Register the singleton, anywhere in your program, when you know what argument to pass.

For example, if you need to register a user object as a singleton, you’ll have to do it after the user logs in and all their info is available in order to properly instantiate your User class.

Solution 2

because it is a singleton you only need to call myClass.name = 'name' once, anywhere in your app and it will change everywhere. example app:

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();

    GetIt.instance.registerLazySingleton<MyClass>(()=> MyClass());

    // Name from a future
    get('https://jsonplaceholder.typicode.com/users').then((response){
      if(response.statusCode==200) {
        setState(() {
          GetIt.I.get<MyClass>().name = jsonDecode(response.body)[0]['name'];
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('Title'),
    ),
    body: Container(
      child: Center(
        child: Text(GetIt.I.get<MyClass>().name),
      ),
    ),
    );
  }
}

class MyClass{
  String name = '';
}

another way is that because it's built using a lazy builder, the MyClass object will only be built after the first locator.get<MyClass>() is called so you can prepare and get it from a static variable.

Share:
2,659
codeKiller
Author by

codeKiller

Updated on December 14, 2022

Comments

  • codeKiller
    codeKiller over 1 year

    I am trying to learn about dependency injection and trying to use it in Flutter/Dart. I have gone through the library get_it which I find very useful.

    But I am having a doubt about the dependency injection in a specific situation.

    If I have a Dart class with parameters like this one for example:

    class MyClass(){
        final String name;
    
        MyClass({this.name})
    
        ....
        ....
    }
    

    In such a class, with parameters, It seems like I cannot use dependency injection? or at least the following using get_it will not work:

    **** service_locator.dart ****

    import 'package:get_it/get_it.dart';
    
    GetIt locator = GetIt();
    
    void setupLocator() {
      locator.registerLazySingleton<MyClass>(() => MyClass());
    }
    

    This gives error on => MyClass()....since it is expecting a parameter.

    How to do this kind of injection?.