skip to Main Content

I have a repository object which I want to use for two blocs (list view bloc and edit dialog bloc). I.e.

class Repo {
  addEntity();
  getEntity();
  fetchEntities();
  ...
}

class ListViewBloc ... {
  final Repo _repo;
}

class EditDialogBloc ... {
  final Repo _repo;
}

The repository object is created in list view widget then passed to ListViewBloc.

On listview selection (tap) I need to open the detail view widget (actually new route) which is managed by the EditDialogBloc.

How can I pass the already create instance of repository to detail route in web using go_router?

I.e. I have a route /#customers which creates a Repo then route switches to /#customers/1 which should use the same Repo. Also it should be taken into account that user may clicks F5 (refresh) and Repo instance must be available

2

Answers


  1. There are 2 most common package to reuse existing Repositories/Services/Data Sources depening on the choosen naming.

    • GetIt – Global instance accessor
    • Provider – Inherited Widget wrapper

    For the usage i advice reading documentation.

    Assuming that your Repositories/Services/Data Sources are not persisting any State you could also create a new instance and pass it into chosen Statebloc in your case.

    Login or Signup to reply.
  2. It seems what you want to do is pass an object from one route to another. You could use the extra parameter:

    context.go('destination-route', extra: repo);
    

    Then in your router definition you will take that parameter from the GoRouterState:

    GoRoute(
        path: 'destination-route',
        name: 'destination-route-name',
        builder: (context, state) {
                return DestinationPageWidget(
                    repo: state.extra,
                );
            },
        )
    

    NOTE: The extra field of the GoRouterState state can be null.

    WARNING: You should NOT use the extra parameter if you are planning to have a Flutter Web app, since it is not ensure to be present. In that case you should use another approach such as passing parameters directly as strings in the URL path or state-management techniques like Riverpod or GetIt

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search