Skip to content

How scopes are meant to work? #158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
shinayser opened this issue Feb 10, 2021 · 2 comments
Closed

How scopes are meant to work? #158

shinayser opened this issue Feb 10, 2021 · 2 comments

Comments

@shinayser
Copy link

shinayser commented Feb 10, 2021

I just put my hands on the library and it is really nice! But I can't find a example of how to work with scopes. The documentation shows no example and in my testes they simply doesn't work like navigators (as mentioned on the readme).

Can someone provide a simple, clean and straightforward piece of code? I am sure this will help others lost as am I.

EDIT: here is my test code:

final getit = GetIt.asNewInstance();

void main(List<String> arguments) async {
  getit.pushNewScope(scopeName: 'cli1');
  getit.registerSingleton<ClientDatabase>(ClientDatabaseImpl(1));
  printClient(); //Prints Client 1

  getit.pushNewScope(scopeName: 'cli2');
  getit.registerSingleton<ClientDatabase>(ClientDatabaseImpl(2));
  printClient(); //Prints Client 2

  getit.popScope(); //Popping to cli1
  printClient(); //Still prints Client 2, but should be printing Client 1 since I've popped!
}

void printClient() =>
    print(getit.get<ClientDatabase>().getCliente()?.toString());

class Client {
  int id;

  Client(this.id);

  @override
  String toString() => 'Client $id';
}

abstract class ClientDatabase {
  Client getCliente();
}

class ClientDatabaseImpl extends ClientDatabase {
  final int id;

  ClientDatabaseImpl(this.id);

  @override
  Client getCliente() => Client(id);
}
@shinayser
Copy link
Author

Seems that my problem was that popScope() runs async way, so It needs to awaited. After that, the code above will work!
Definetly a simple sample on the README file will be helpful for future users.

@escamoteur
Copy link
Collaborator

I agree, that part is a bit tricky. Little tip, often its helpful to take a look into the tests for a feature.
If you want to add a small example to the readme, I'm happy to get a PR ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants