Lazy instantiate blocks with BlocProvider.value

Issue

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

Solution

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?

Answered By – Enzo Dtz

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *