Home Cubit

Learn how to use Cubits to conditionally show different widgets in your app.

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 BottomNavigationBar in the home screen, and render the correct AppBar and body of the page.

The available bodies are declared in lib\screens\home_screen\home_screen.dart:

Press + to interact
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 AppBar that is shown to the user.

  • The current index for the BottomNavigationBar.

  • The current Scaffold body 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.

Press + to interact
abstract class HomeState {
PreferredSizeWidget currentAppBar;
int currentBottomNavigationIndex;
Widget currentBody;
List<Category> categories = [];
HomeState({
// The current AppBar that is shown to the user
required this.currentAppBar,
// The current index for the BottomNavigationIndex
required this.currentBottomNavigationIndex,
// The current Scaffold body that will be shown to the user
required this.currentBody,
// The list of categories that we get from the products repository
required this.categories,
});
}
  • Lines 2–5: Define the properties of the HomeState abstract class, which is used to keep track of the current state of the e-commerce app.

  • Line 2: The currentAppBar property is used to store the PreferredSizeWidget of the current AppBar being displayed to the user.

  • Line 3: The currentBottomNavigationIndex property is used to keep track of the index of the current BottomNavigationBar.

  • Line 4: The currentBody property is used to store the current Scaffold body being displayed to the user.

  • Line 5: The categories property is a list of Category ...

Access this course and 1400+ top-rated courses and projects.