Question: How to handle Flutter widget rebuilding with BLOC?
In regards to Flutter's way to rebuild widgets when navigating between routes, there is this issue: Pages on Navigator stack rebuild when a new page is pushed where the dev team and others provided these interesting insights:
This is working as intended. In general, you should assume that all widgets can rebuild at any time, flutter error that they don't is mostly just an optimization. [...]
You should generally assume that every widget will be rebuilt flutter error every frame, and design your build methods to be idempotent [...]
you'll need to restructure your code so that the data is not fetched again [...].
I am using BLoC to fetch remote data. For example, in my HomePage
:
class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocBuilder<HomeBloc, HomeState>( bloc: sl.get()..add(const GetHomeEvent()), // `sl` from package `GetIt`, a dependency injector builder: (context, state) { return AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: state.join( (initial) => const EmptyHome(), (loading) => const LoadingHome(), (success) => LoadedHome(homeEntity: success.homeEntity), (failure) => FailedHome(errorMessage: failure.message), ), ); }, ); }
As you can read, I build a BlocBuilder
and upon its instantiation, I asked the HomeBloc
to fetch data:
HomeBloc() : super(HomeState.initial()) { on<GetHomeEvent>((event, emit) async { print('load home event request'); // code to load home and notify of result via `emit()` ); });
The log load home event request
gets printed multiple times as I navigate in and out from my home page.
How should I go about and prevent unnecessarily reloading the home ?
- Should I simply cache it via a local variable?
- How to handle refresh properly (e.g. hit F5 in the web browser)?