Enzo Dtz
Enzo Dtz

Reputation: 381

Lazy instantiate blocks with BlocProvider.value

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;
    }
  }
}

Upvotes: 0

Views: 1139

Answers (1)

Enzo Dtz
Enzo Dtz

Reputation: 381

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?

Upvotes: 3

Related Questions