12.2 轮播图
实现步骤:
第 1 步:api 拉取商品数据
lib/common/api/product.dart
1 2 3 4 5 6 7
| static Future<ProductModel> productDetail(int? id) async { var res = await WPHttpService.to.get( '/products/$id', ); return ProductModel.fromJson(res.data); }
|
第 2 步:控制器
lib/pages/goods/product_details/controller.dart
1 2 3 4 5 6 7 8
| int? productId = Get.arguments['id'] ?? 0;
ProductModel? product;
List<KeyValueModel> bannerItems = [];
int bannerCurrentIndex = 0;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| _loadProduct() async { product = await ProductApi.productDetail(productId);
if (product?.images != null) { bannerItems = product!.images! .map<KeyValueModel>((e) => KeyValueModel( key: "${e.id}", value: e.src ?? "", )) .toList(); } }
|
1 2 3 4 5
| _initData() async { await _loadProduct();
update(["product_details"]); }
|
1 2 3 4 5
| void onChangeBanner(int index, _reason) { bannerCurrentIndex = index; update(["product_banner"]); }
|
第 3 步:视图
lib/pages/goods/product_details/view.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| Widget _buildBanner() { return GetBuilder<ProductDetailsController>( id: "product_banner", tag: tag, builder: (_) { return CarouselWidget( items: controller.bannerItems, currentIndex: controller.bannerCurrentIndex, onPageChanged: controller.onChangeBanner, height: 190.w, indicatorCircle: false, indicatorAlignment: MainAxisAlignment.start, indicatorColor: AppColors.highlight, ); }).backgroundColor(AppColors.surfaceVariant); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Widget _buildView() { return controller.product == null ? const PlaceholdWidget() : <Widget>[ _buildBanner(),
_buildTitle(),
_buildTabBar(),
_buildTabView(), ].toColumn(); }
|
1 2 3 4 5 6 7 8 9
| @override Widget build(BuildContext context) { ... builder: (_) { return Scaffold( appBar: mainAppBarWidget( titleString: controller.product?.name ?? LocaleKeys.gDetailTitle.tr),
|
提交代码到 git