【问题标题】:How do I return the first five values from JSON response DART如何从 JSON 响应 DART 返回前五个值
【发布时间】:2021-09-30 05:42:15
【问题描述】:

我想从上面的 JSON 响应中返回 name 的前五个值

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) => new UserModel.fromJson(user)).toList();
    
  } else {
    throw Exception('Unexpected error occured!');
  }
}

这是下面的模型。

class UserModel {
  int id;
  String name;

  UserModel({
    required this.id,
    required this.name,

  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'],
      name: json['name'],

    );
  }
}

API 在列表中有几个值,我想只返回前 5 个

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    如果我理解正确,你可以这样做:

    jsonResponse.map((user) => new UserModel 
                    .fromJson(user))
                    // this will take only the first five elements of the iterable
                    .take(5)
                    // this will map each user to its corresponding name
                    .map((user) => user.name)
                    // this, as you already know, will convert the iterable to a list
                    .toList();
    

    这将返回一个包含前五个名称的List&lt;String&gt;

    【讨论】:

    • 你太棒了。
    • 谢谢 :D,如果这是你想要的,请接受答案
    猜你喜欢
    • 2013-06-16
    • 2019-03-27
    • 2018-12-24
    • 2017-09-13
    • 2013-08-22
    • 2015-12-27
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多