How to take a certain data index of Future<List> item

Viewed 459

I Have a problem to take the newest data index

class User {
  final String idUser,
  name,
  phone;

  User(
    {this.idUser,
    this.name,
    this.phone});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
    idUser: json['_id'],
    name: json['name'],
    phone: json['phone']);
  }
}

List<User> userFromJson(jsonData) {
  List<User> result =
    List<User>.from(jsonData.map((item) => User.fromJson(item)));

  return result;
}

// index
Future<List<User>> fetchUser() async {
  String route = AppConfig.API_ENDPOINT + "userdata";
  final response = await http.get(route);
  if (response.statusCode == 200) {
    var jsonResp = json.decode(response.body);

    return userFromJson(jsonResp);
  } else {
    throw Exception('Failed load $route, status : ${response.statusCode}');
  }
}

and the calling method just like this

user = fetchUser();

the "response.body" valued like this

[{"_id":"4136425eb8d9320f4822c554","name":"John","phone":"90643755394"},{"_id":"62766b2eb45s3w0g4662ftd3","name":"Anna","timestamp":"90345765791"}]

I expect it was how to take the first index to get the newest data, but I don't know ho the code will be. Also if there are another soltion to get that newest data, please let me know, thank you very much

3 Answers

You can use array index number to get the first object in array.

 if (response.statusCode == 200) {
    var jsonResp = json.decode(response.body);

    return List<User>.from(jsonResp.map((user) => User.fromJson(user)));
  } else {
    throw Exception('Failed load $route, status : ${response.statusCode}');
  }

If you want to get one user only

 if (response.statusCode == 200) {
    var jsonResp = json.decode(response.body);

    return User.fromJson(jsonResp[0]);
  } else {
    throw Exception('Failed load $route, status : ${response.statusCode}');
  }

Other method is by modifying the Query using LIMIT 1

Use index to get the specific value from a list

userFromJson(jsonResp[0]); /// For first record

Because its Future You have to use the await keyword to get the completed result so modify your code by adding await

users = await fetchUser();

now you can access the user list

var firstUser = users.first;
var firstUser = users[0];

For more await and async you can read this Asynchronous programming

Related