Home Cubit
Learn how to use Cubits to conditionally show different widgets in your app.
We'll cover the following...
The HomeCubit is the second Cubit that needs to be implemented in our e-commerce app. It helps us accomplish the following tasks:
Retrieve the list of categories and products from the products repository.
Change pages using the
BottomNavigationBarin the home screen, and render the correctAppBarand body of the page.
The available bodies are declared in lib\screens\home_screen\home_screen.dart:
final List<Widget> widgetOptions = [SingleChildScrollView(child: ListView(shrinkWrap: true,physics: const ScrollPhysics(),scrollDirection: Axis.vertical,children: const [CategoriesGrid(),],),),const CartScreen(),];
Implementing HomeState
The state of our app should keep track of the following:
The current
AppBarthat is shown to the user.The current index for the
BottomNavigationBar.The current
Scaffoldbody that will be shown to the user.The list of categories that we get from the products repository
Let's define the HomeState abstract class.
abstract class HomeState {PreferredSizeWidget currentAppBar;int currentBottomNavigationIndex;Widget currentBody;List<Category> categories = [];HomeState({// The current AppBar that is shown to the userrequired this.currentAppBar,// The current index for the BottomNavigationIndexrequired this.currentBottomNavigationIndex,// The current Scaffold body that will be shown to the userrequired this.currentBody,// The list of categories that we get from the products repositoryrequired this.categories,});}
Lines 2–5: Define the properties of the
HomeStateabstract class, which is used to keep track of the current state of the e-commerce app.Line 2: The
currentAppBarproperty is used to store thePreferredSizeWidgetof the currentAppBarbeing displayed to the user.Line 3: The
currentBottomNavigationIndexproperty is used to keep track of the index of the currentBottomNavigationBar.Line 4: The
currentBodyproperty is used to store the currentScaffoldbody being displayed to the user.Line 5: The
categoriesproperty is a list ofCategoryobjects obtained from the products repository. ...