0

I'm using Generated Routes with Flutter, and I would like to share blocs between them.

But I think that maybe the example solution might not scale the best, since the blocs are instantiated with the router.

Is there a way to instantiate them only when the user access that route?

class AppRouter {
  final _counterBloc = CounterBloc();

  Route onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
          builder: (_) => BlocProvider.value(
            value: _counterBloc,
            child: HomePage(),
          ),
        );
      case '/counter':
        return MaterialPageRoute(
          builder: (_) => BlocProvider.value(
            value: _counterBloc,
            child: CounterPage(),
          ),
        );
      default:
        return null;
    }
  }
}

Enzo Dtz
  • 361
  • 1
  • 16
  • 1
    If you are sharing blocs between all your routes, build them above your `Navigator`. – Abion47 Jun 02 '21 at 19:46
  • Wouldn't it generate lots of boilerplate? – Enzo Dtz Jun 02 '21 at 20:15
  • Why would it generate boilerplate? – Abion47 Jun 02 '21 at 20:16
  • 1
    I thought I would need to use something like define it as null and then check if null to instantiate on every route, but seems that I can use `late` declaration on it to instantiate it only when called. – Enzo Dtz Jun 02 '21 at 20:24
  • Why would you need to instantiate it on every route? Every route is pointing to the same bloc, right? Then wrap your `Navigator` in a `BlocProvider` so that every route implicitly has access to it. Don't even worry about messing it on a per-route basis. – Abion47 Jun 02 '21 at 20:27
  • Does this answer your question: https://stackoverflow.com/questions/67585543/flutter-how-to-use-exist-bloc-for-other-screens/67588687? – mkobuolys Jun 02 '21 at 20:40

1 Answers1

3

Got it! Flutter has a new keyword called late to do this without any boilerplate.

class AppRouter {
  late final CounterBloc _counterBloc = CounterBloc();

  Route onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(
          builder: (_) => BlocProvider.value(
            value: _counterBloc,
            child: HomePage(),
          ),
        );
      case '/counter':
        return MaterialPageRoute(
          builder: (_) => BlocProvider.value(
            value: _counterBloc,
            child: CounterPage(),
          ),
        );
      default:
        return null;
    }
  }
}

That's why we love flutter!

Reference: What is Null Safety in Dart?

Enzo Dtz
  • 361
  • 1
  • 16