I have following code in flutter. It is working as expected. I have a services class. It has a getList method. This method returns a List of User.
import 'package:http/http.dart' as http;
const ROOT = 'http://localhost/app/users.php';
class User{
final String id;
final String name;
User({
this.id,
this.name,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as String,
name: json['name'] as String,
);
}
}
class Services {
Future<List<User>> getList() async {
try {
var map = new Map<String, dynamic>();
map["action"] = "fetch-all";
final response = await http.post(ROOT, body: map);
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
List<User> list = parsed.map<User>((json) => User.fromJson(json)).toList();
return list;
} else {
throw List<User>();
}
} catch (e) {
return List<User>();
}
}
}
I am trying to make a generic method from above code. I can pass any object type (eg: User in this above code) in getList() method as parameter and get the output list this object passed in as parameter.
Eg: Instead of User object is can pass Album Object as parameter and I can get a List of Album as output.
May Be something like this method:
Future<List> getList({Map map, MyClass}) async {
final response = await http.post(ROOT, body: map);
print("getUsers >> Response:: ${response.body}");
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
return parsed.map<MyClass>((json) => User.fromJson(json)).toList();
} else {
print("no data");
throw List<MyClass>();
}
}
Here MyClass is a dynamic Object that can be passed.