Home > database >  How do I return the first five values from JSON response DART
How do I return the first five values from JSON response DART

Time:10-01

I would like to return the first five value of name from the JSON response above

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!');
  }
}

Here's the model below.

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 has several values in the list and I'd like to return the first 5 only

CodePudding user response:

if i understood correctly, you can do something like this:

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();

this will return a List<String> containing the first five names

  • Related