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();
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
CodePudding user response:
You can use array index number to get the first object in array.
if (response.statusCode == 200) {
var jsonResp = json.decode(response.body);
return userFromJson(jsonResp[0]);
} else {
throw Exception('Failed load $route, status : ${response.statusCode}');
}
Other method is by modifying the Query using LIMIT 1
CodePudding user response:
Use index to get the specific value from a list
userFromJson(jsonResp[0]); /// For first record