11.1 左侧导航栏组件
效果
 
实现步骤:
第 1 步:i18n
lib/common/i18n/locale_keys.dart
| 12
 
 | static const gCategoryTitle = "goods_category_title";
 
 | 
lib/common/i18n/locales/locale_en.dart
| 12
 
 | LocaleKeys.gCategoryTitle: 'All Categories',
 
 | 
lib/common/i18n/locales/locale_zh.dart
| 12
 
 | LocaleKeys.gCategoryTitle: '所有分类',
 
 | 
第 2 步:分类数据缓存读取
lib/common/values/constants.dart
| 12
 3
 
 | 
 static const storageProductsCategories = 'home_categories';
 
 | 
lib/pages/goods/home/controller.dart
| 12
 3
 4
 
 | Future<void> _initData() async {
 
 Storage().setJson(Constants.storageProductsCategories, categoryItems);
 
 | 
第 3 步:控制器
lib/pages/goods/category/controller.dart
| 12
 
 | int? categoryId = Get.arguments['id'];
 
 | 
| 12
 
 | List<CategoryModel> categoryItems = [];
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | _initData() async {
 
 var stringCategories =
 Storage().getString(Constants.storageProductsCategories);
 categoryItems = stringCategories != ""
 ? jsonDecode(stringCategories).map<CategoryModel>((item) {
 return CategoryModel.fromJson(item);
 }).toList()
 : [];
 
 
 if (categoryItems.isEmpty) {
 categoryItems = await ProductApi.categories();
 }
 
 update(["left_nav"]);
 }
 
 | 
| 12
 3
 4
 5
 
 | void onCategoryTap(int id) async {
 categoryId = id;
 update(["left_nav"]);
 }
 
 | 
第 4 步:视图
lib/pages/goods/category/view.dart
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 
 | Widget _buildLeftNav() {
 return GetBuilder<CategoryController>(
 id: "left_nav",
 builder: (_) {
 return ListView.separated(
 itemBuilder: (context, index) {
 var item = controller.categoryItems[index];
 return CategoryListItemWidget(
 category: item,
 selectId: controller.categoryId,
 onTap: controller.onCategoryTap,
 );
 },
 separatorBuilder: (context, index) {
 return SizedBox(height: AppSpace.listRow.w);
 },
 itemCount: controller.categoryItems.length,
 )
 
 .width(100.w)
 
 
 .decorated(
 color: AppColors.surfaceVariant,
 )
 
 
 .clipRRect(
 topRight: AppRadius.card.w,
 bottomRight: AppRadius.card.w,
 );
 },
 );
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 
 | Widget _buildView() {
 return <Widget>[
 
 _buildLeftNav(),
 
 ].toRow();
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | @overrideWidget build(BuildContext context) {
 return GetBuilder<CategoryController>(
 init: CategoryController(),
 id: "category",
 builder: (_) {
 return Scaffold(
 
 appBar: mainAppBarWidget(
 titleString: LocaleKeys.gCategoryTitle.tr,
 ),
 
 body: SafeArea(
 child: _buildView(),
 ),
 );
 },
 );
 }
 
 | 
第 5 步:首页分类点击
lib/pages/goods/home/controller.dart
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | void onCategoryTap(int categoryId) {
 Get.toNamed(
 RouteNames.goodsCategory,
 arguments: {
 "id": categoryId,
 },
 );
 }
 
 | 
提交代码到 git