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

Dart开发中如何从接口JSON响应结果中返回前5条name字段值

方案1:返回前5条UserModel实例

直接在现有代码基础上,调用Dart内置的take()方法截取前5条元素即可,该方法在接口返回数据不足5条时会自动返回全部可用数据,不会触发越界错误:

Future <List<UserModel>> fetchData() async {
  final response =
      await http.get(Uri.parse(URLCONST.API_URL));
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((user) => UserModel.fromJson(user)).take(5).toList();
  } else {
    throw Exception('Unexpected error occured!');
  }
}

方案2:直接提取前5条的name字段值返回

如果你只需要name字段的字符串列表,可以修改方法返回类型,直接提取字段值:

Future <List<String>> fetchTop5Names() async {
  final response =
      await http.get(Uri.parse(URLCONST.API_URL));
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse
        .map((user) => UserModel.fromJson(user).name)
        .take(5)
        .toList();
  } else {
    throw Exception('Unexpected error occured!');
  }
}

如果不需要走模型类转换,也可以直接从JSON结构取值,性能更优:

return jsonResponse.map((user) => user['name'] as String).take(5).toList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:09:02