kauemurakami / getx_pattern

Design pattern designed to standardize your projects with GetX on Flutter.
https://kauemurakami.github.io/getx_pattern
1k stars 235 forks source link

How to use multiple repositories on a single controller ? #8

Closed mandreshope closed 4 years ago

kauemurakami commented 4 years ago

705/5000 Hello Mandreshop, it's simpler than you can imagine, just add another required attribute to your controller, in this case a repository.

It is very common to use more than one repository for some things, such as assigning a task to a user of the app through its controller, we would need to retrieve a user (with UserRepository and its proper functions for example), create a task (TaskRepository), and we also have a table / entity to make this connection, in this example I will say UserTasksRepository, for example.

So you just need to use the bindings for this, but first you must add this attribute in your controller as well as your first repository, like this:

  ExampleController({
      @required this.userRepository, 
      @required this.taskRepository,
      @required this.userTaskRepository})
      : assert(userRepository != null, taskRepository != null, userTaskRepository != null);

Now let's start them together with the controller in our binding file:

class ExampleBinding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut<ExampleController>(() => ExampleController(
        userRepository: UserRepository(...), taskRepository: TaskRepository(...), userTaskRepository: UserTask(...) )));
  }
}

If you don't use bindings, you can simply boot into your controller.

I'll leave it open until the end of the day, if you have any other questions, I'm available.

mandreshope commented 4 years ago

@kauemurakami Very clear, thanks for your help. 😊