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
BottomNavigationBar
in the home screen, and render the correctAppBar
and 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
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.
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
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 thePreferredSizeWidget
of the currentAppBar
being displayed to the user.Line 3: The
currentBottomNavigationIndex
property is used to keep track of the index of the currentBottomNavigationBar
.Line 4: The
currentBody
property is used to store the currentScaffold
body being displayed to the user.Line 5: The
categories
property is a list ofCategory
...