You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何实现基于kontenId的动态onTap跳转(替代静态判断)

解决Flutter中根据kontenId动态跳转详情页并获取数据的问题

一、简化列表页的跳转逻辑

原来的onTap里通过多个if-else判断kontenId,但所有分支的跳转逻辑完全一致,直接提取kontenId后统一处理即可,无需逐个判断:

修改ListProduct中的onTap代码:

onTap: () {
  final currentKontenId = productController.productList[index].kontenId;
  // 检查控制器中是否存在该kontenId对应的详情数据
  if (productController.productMap.containsKey(currentKontenId)) {
    Get.to(
      () => ProductDetailListView(
        product: productController.productList[index],
      ),
      arguments: currentKontenId,
    );
  } else {
    Get.snackbar("Data Kosong", "Data masih kosong");
  }
}

二、重构控制器,用Map存储不同kontenId的详情数据

把原来分散的productList1、productList2、productList3替换成一个Map<String, List<ProductModel>>,通过kontenId直接映射到对应的列表,避免后续新增kontenId时重复添加分支:

修改ProductController:

class ProductController extends GetxController {
  var productList = <ProductModel>[].obs; // 主列表数据
  var productMap = <String, List<ProductModel>>{}.obs; // 详情数据映射,key为kontenId
  var isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    fetchAllData();
  }

  // 统一获取所有数据
  Future<void> fetchAllData() async {
    isLoading.value = true;
    // 模拟获取主列表数据(替换成你的实际API请求)
    productList.value = await fetchMainList();
    
    // 按kontenId获取详情数据并存入Map
    final kontenIds = productList.map((item) => item.kontenId).toSet();
    for (var id in kontenIds) {
      productMap[id] = await fetchDetailData(id);
    }
    isLoading.value = false;
  }

  // 获取主列表数据的方法(替换成你的实际API请求)
  Future<List<ProductModel>> fetchMainList() async {
    // 示例逻辑,实际替换为接口请求
    return [];
  }

  // 根据kontenId获取详情数据的方法(替换成你的实际API请求)
  Future<List<ProductModel>> fetchDetailData(String kontenId) async {
    // 示例逻辑,实际根据kontenId请求对应数据
    return [];
  }
}

三、改造详情页,动态获取对应数据

利用控制器中的productMap,通过传入的kontenId直接获取对应列表,去掉所有if-else判断:

修改ProductDetailListView:

class ProductDetailListView extends GetView<ProductController> {
  final ProductModel product;
  ProductDetailListView({this.product});

  final String kontenId = Get.arguments;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(product.kontenMenu),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            bottom: Radius.circular(30),
          ),
        ),
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        // 通过kontenId获取对应详情列表,为空则显示提示
        final detailList = controller.productMap[kontenId] ?? [];
        return detailList.isEmpty
            ? const Center(child: Text('Belum ada data'))
            : Expanded(
                child: ListView.builder(
                  itemCount: detailList.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {},
                      child: Card(
                        elevation: 5,
                        margin: const EdgeInsets.all(10),
                        child: ListTile(
                          title: Text(detailList[index].kontenMenu),
                        ),
                      ),
                    );
                  },
                ),
              );
      }),
    );
  }
}

核心优化点

  • 用Map映射替代多个独立列表,实现kontenId到数据的动态关联
  • 移除所有硬编码的kontenId判断,后续新增kontenId无需修改页面逻辑,只需保证接口返回对应数据
  • 统一数据获取逻辑,提升代码可维护性

内容的提问来源于stack exchange,提问作者JustPeople

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:35:19