How to handle Flutter widget rebuilding with BLOC?

120

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:

  1. About this reported behavior in the issue itself:

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. [...]

  1. Further (re)explained here:

You should generally assume that every widget will be rebuilt flutter error every frame, and design your build methods to be idempotent [...]

  1. When asked how to handle fetching data in build(context):

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)?

Total Answers: 1

15

Answers 1: of How to handle Flutter widget rebuilding with BLOC?

build method is such a method which will be executed frequently. For screen pages who need to fetch some data, it is prefereed to create stateful widget instead of stateless. And then you should add event on bloc inside initState method instead of build. Don’t forget to delete ..({event}) in build methos. In that way you will get flutter error rid off problem with unnecessary API requests.