How to pass same widget to all states in a blocs builder

Issue

Let’s suppose i have the following bloc builder:

    return BlocListener<LoginBloc, LoginState>(listener: (context, state) {
  if (state is ErrorLoginState) {
    showError(state.message, context);
  }
}, child: BlocBuilder<LoginBloc, LoginState>(
  builder: (context, state) {
    if (state is StartLogin) {
      return Center(
        child: Loading(),
      );
    }

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
        child: Container(),
      ),
    );
  },
));

How could i pass the same widget, like a search bar, to all states rendering? The only way would be putting his code in all states conditionals?

Solution

I’ve managed to do it like that:

Widget build(BuildContext context){ 
       return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        padding: EdgeInsets.symmetric(vertical: 20.0, horizontal:                     50.0),
        child: SizedBox(
                children: [
                    _showSearch(),
                ]),
      ),
  );
}

Widget _showSearch() {  
    return BlocListener<SearchBloc, SearchState>(          
        child: BlocBuilder<SearchBloc, SearchState>(        
            builder: (context, state) {          
                if (state is SearchInitial) {            
                    return SearchHome();          
                } else if (state is SuccessFilterState) {            
                    return SearchResult(opportunityList:       state.opportunityList);                       
                } else {            
                    return ErrorSearch();          
                }        
            },      
        ),    
    );  
}

Answered By – Gabriel Reis

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.