You need to enable JavaScript to run this app. Flutter如何基于本地JSON数据实现动态Tab Bar及对应列表页
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何基于本地JSON数据实现动态Tab Bar及对应列表页

问题原因
  • 类型转换错误:Dart中Map的keys属性返回Iterable迭代器类型,你代码中(newData.keys as List)的强制转换不合法,直接触发_CastError。
  • JSON解析逻辑错误:你的JSON根结构是数组,每个数组元素对应一个分类的单键Map,你当前仅取了数组第一个元素json.decode(...)[0],会丢失Fruits、Bakery等其余4个分类,Tab数量不全。
修复代码

直接替换你的ParsingJson类代码即可,修复后自动生成所有分类Tab,且对应页面可直接拿到对应分类的商品列表,你可以直接接入已开发完成的ListView组件:

import 'dart:convert';

import 'package:flutter/material.dart';

class ParsingJson extends StatefulWidget {
  const ParsingJson({Key? key}) : super(key: key);

  @override
  _ParsingJsonState createState() => _ParsingJsonState();
}

class _ParsingJsonState extends State<ParsingJson> {
  late Future<String> jsonString;
  int _initPosition = 0;

  @override
  void initState() {
    super.initState();
    jsonString = DefaultAssetBundle.of(context)
        .loadString("assets/json_file/categories.json");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("JSON parsing demo"),
        ),
        body: SafeArea(
            child: FutureBuilder(
                future: jsonString,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    // 解析JSON根数组
                    List jsonList = json.decode(snapshot.data.toString());
                    // 提取所有分类的键值对为统一列表,方便Tab和页面绑定
                    List<MapEntry<String, List<dynamic>>> categories = [];
                    for (var categoryItem in jsonList) {
                      categoryItem.forEach((categoryName, productList) {
                        categories.add(MapEntry(categoryName, productList));
                      });
                    }
                    return CustomTabView(
                      initPosition: _initPosition,
                      itemCount: categories.length,
                      tabBuilder: (context, index) =>
                          Tab(text: categories[index].key),
                      pageBuilder: (context, index) {
                        // 此处直接获取当前分类对应的商品列表,可替换为你自定义的ListView代码
                        final productList = categories[index].value;
                        return ListView.builder(
                          padding: const EdgeInsets.all(12),
                          itemCount: productList.length,
                          itemBuilder: (context, productIndex) {
                            final product = productList[productIndex];
                            return ListTile(
                              leading: Image.asset(product['imageUrl'], width: 50, height: 50, fit: BoxFit.cover),
                              title: Text(product['name']),
                              subtitle: Text(product['description']),
                              trailing: Text('¥${product['pricePerKg']}/kg'),
                            );
                          },
                        );
                      },
                      onPositionChange: (index) {
                        _initPosition = index;
                      },
                      onScroll: (position) {},
                    );
                  }
                  return const Center(child: CircularProgressIndicator());
                })));
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 08:30:03