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

Flutter执行list.map转DataModel列表时数据丢失问题求助

问题根因

你的代码存在3个直接导致解析失败的问题:

  • DataModel.fromJson 工厂方法中,print 语句写在了return之后,属于永远不会执行的死代码;同时你在类中声明了createdAt字段,却没有在构造方法和fromJson里做初始化,本身就存在类型隐患。
  • 你把catch块中的错误打印语句注释掉了:Mock接口返回的price/people/stars字段大概率是String类型,和你声明的int类型不匹配,赋值时会直接抛出类型转换异常,异常被catch捕获后静默返回空数组,你看不到任何报错信息,自然会误以为数据在map转换时丢失了。
  • getInfo 方法只声明了返回Future<List>,没有指定泛型为List<DataModel>,缺失类型校验,很多本可以在编译期发现的问题被拖到了运行时。
修复方案

修正后的DataModel代码

class DataModel {
  String name;
  String img;
  int price;
  int people;
  int stars;
  String description;
  String location;
  dynamic createdAt;

  DataModel({
    required this.name,
    required this.img,
    required this.price,
    required this.people,
    required this.stars,
    required this.description,
    required this.location,
    this.createdAt, // 设为可选参数,不需要强制必填
  });

  factory DataModel.fromJson(Map<String, dynamic> json) {
    // 打印语句必须放在return之前才能正常执行
    print('Données du model $json');
    return DataModel(
      // 做空值兜底,避免字段为null时抛出空指针错误
      name: json["name"] ?? "",
      img: json["img"] ?? "",
      // 做类型兼容处理,无论接口返回int还是String类型的数字,都能安全转为int
      price: int.parse(json["price"].toString()),
      people: int.parse(json["people"].toString()),
      stars: int.parse(json["stars"].toString()),
      description: json["description"] ?? "",
      location: json["location"] ?? "",
      createdAt: json["createdAt"],
    );
  }
}

修正后的DataServices代码

import 'dart:convert';

import 'package:flutter_cubit/model/data_model.dart';
import 'package:http/http.dart' as http;

class DataServices {
  String baseUrl = "https://61f969ae69307000176f7243.mockapi.io";
  // 明确指定返回值泛型,开启类型校验
  Future<List<DataModel>> getInfo() async {
    var apiUrl = '/DevMobile';
    http.Response res = await http.get(Uri.parse(baseUrl + apiUrl));

    try {
      if (res.statusCode == 200) {
        List<dynamic> list = json.decode(res.body);
        print('donnees service non formaté $list');
        return list.map((e) => DataModel.fromJson(e)).toList();
      } else {
        return <DataModel>[];
      }
    } catch (e) {
      // 不要注释错误打印,否则运行时出问题完全没有排查线索
      print('JSON解析报错: $e');
      return <DataModel>[];
    }
  }
}
注意事项
  • 所有写在return语句之后的代码都不会被执行,写代码时要注意逻辑顺序
  • 解析外部接口返回的JSON时,一定要做空值兜底和类型兼容,不要假设接口返回的类型和你预想的完全一致
  • 捕获异常时不要直接吞掉错误,至少打印错误日志,否则排查问题会浪费大量时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 11:00:59