You need to enable JavaScript to run this app. Flutter用ListView.builder解析JSON嵌套workout实现个人档案页展示
优惠活动
大模型
产品
解决方案
定价
更多

Flutter用ListView.builder解析JSON嵌套workout实现个人档案页展示

嵌套JSON提取与跨页传参实现方案

嵌套workout子列表的提取逻辑

核心思路是在JSON解析阶段完成嵌套结构的类型转换,不需要等到渲染阶段临时取值:

  • 针对嵌套的workout列表单独定义匹配的Dart实体类,逐字段映射JSON结构
  • 对应用户层级的JSON节点,先读取顶层的displayName/age/peso/altezza字段,再定位到workout对应的数组节点,遍历数组内的每个子项,转换为训练实体存入用户对象的workout属性
  • 相比直接操作Map取值的写法,实体类解析可以规避类型不匹配的运行时错误,长期维护场景更推荐这种方式,后续调整字段也更方便

跨页面传递完整用户数据的实现

Flutter路由的传参机制原生支持传递自定义实体对象,不需要做额外的序列化转换:

  • 列表项的点击回调中,将当前渲染的、已经解析完成的完整用户对象(包含workout列表)作为路由参数传入跳转路径
  • 目标Profile页通过路由参数接口读取传递的用户实例,即可直接调用实例上的所有属性,包括嵌套的workout列表完成渲染

核心实现代码示例

  1. 定义匹配JSON结构的实体类
// 训练子项模型
class Workout {
  final String nomeworkout;
  Workout({required this.nomeworkout});

  factory Workout.fromJson(Map<String, dynamic> json) => Workout(
    nomeworkout: json['nomeworkout'] as String,
  );
}

// 用户主模型
class User {
  final String displayName;
  final int age;
  final double peso;
  final double altezza;
  final List<Workout> workout;

  User({
    required this.displayName,
    required this.age,
    required this.peso,
    required this.altezza,
    required this.workout,
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
    displayName: json['displayName'] as String,
    age: json['age'] as int,
    peso: (json['peso'] as num).toDouble(),
    altezza: (json['altezza'] as num).toDouble(),
    // 嵌套workout列表的核心提取逻辑
    workout: (json['workout'] as List<dynamic>).map(
      (item) => Workout.fromJson(item as Map<String, dynamic>)
    ).toList(),
  );
}
  1. 调整本地JSON加载逻辑
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;

Future<List<User>> loadLocalUserData() async {
  // 读取assets下的jsonDb.json资源
  final jsonContent = await rootBundle.loadString('assets/jsonDb.json');
  final jsonArray = json.decode(jsonContent) as List<dynamic>;
  // 全量转换为User对象列表
  return jsonArray.map(
    (userNode) => User.fromJson(userNode as Map<String, dynamic>)
  ).toList();
}
  1. 列表跳转时传递完整用户对象
// HomePage内的ListView.builder实现
ListView.builder(
  itemCount: userList.length,
  itemBuilder: (context, index) {
    final user = userList[index];
    return ListTile(
      title: Text(user.displayName),
      subtitle: Text('年龄 ${user.age}'),
      onTap: () {
        // 直接将完整的user对象(含workout列表)作为路由参数传递
        Navigator.pushNamed(
          context,
          '/profile',
          arguments: user,
        );
      },
    );
  },
)
  1. Profile页读取参数并渲染嵌套数据
class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    // 读取路由传递的用户对象
    final User user = ModalRoute.of(context)!.settings.arguments as User;
    return Scaffold(
      appBar: AppBar(title: Text(user.displayName)),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Text('年龄: ${user.age}'),
          Text('体重(peso): ${user.peso}'),
          Text('身高(altezza): ${user.altezza}'),
          const SizedBox(height: 24),
          const Text('训练内容列表', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
          // 遍历展示嵌套的workout数据
          ...user.workout.map(
            (workout) => ListTile(
              leading: const Icon(Icons.fitness_center),
              title: Text(workout.nomeworkout),
            )
          )
        ],
      ),
    );
  }
}

注意事项

  • 如果项目中JSON结构比较复杂,可以借助官方工具链自动生成实体类的解析代码,减少手写映射的工作量
  • 读取路由参数时确保类型匹配,避免因为传递类型和强转类型不一致导致的运行时异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 04:36:03