Home > OS >  Error fetching API / A value of type 'List<Heroes>' can't be returned from the
Error fetching API / A value of type 'List<Heroes>' can't be returned from the

Time:07-23

im new in Dart/Flutter and im struggling with consuming API, here is my file thats inside my model folder:

List<Heroes> heroesFromJson(String str) =>
    List<Heroes>.from(json.decode(str).map((x) => Heroes.fromJson(x)));

String heroesToJson(List<Heroes> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Heroes {
  Heroes({
    required this.id,
    required this.name,
    required this.localizedName,
    required this.primaryAttr,
    required this.attackType,
    required this.roles,
  });

  int id;
  String name;
  String localizedName;
  String primaryAttr;
  String attackType;
  List<String> roles;

  factory Heroes.fromJson(Map<String, dynamic> json) => Heroes(
        id: json["id"],
        name: json["name"],
        localizedName: json["localized_name"],
        primaryAttr: json["primary_attr"],
        attackType: json["attack_type"],
        roles: List<String>.from(json["roles"].map((x) => x)),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "localized_name": localizedName,
        "primary_attr": primaryAttr,
        "attack_type": attackType,
        "roles": List<dynamic>.from(roles.map((x) => x)),
      };
}

And here is where im getting the error, inside services folder:

class DotaServices {
  Future<List<String>?> getHeroes() async {
    var client = http.Client();
    var url = Uri.parse('https://api.opendota.com/api/heroes');
    var response = await client.get(url);
    if (response.statusCode == 200) {
      var json = response.body;
      return heroesFromJson(json);
    }
  }
}

The error is occuring in that line:

return heroesFromJson(json);

And the message that appears is:

A value of type 'List<Heroes>' can't be returned from the method 'getHeroes' because it has a return type of 'Future<List<String>?>'.

how to solve it? Im struggling real hard on this :/

CodePudding user response:

Your method returns a list of heroes... so... you need to return a list of heroes:

Future<List<String>?> getHeroes() async {

needs to be

Future<List<Heroes>?> getHeroes() async {

CodePudding user response:

heroesFromJson returns a list of heroes so getHeroes has to return a list of heroes:

Future<List<Heroes>?> getHeroes()

Also, your method heroesFromJson returns a List<Heroes> not nullable, but your method getHeroes() return a List<Heroe>? which is nullable.

You either can make your return from heroesFromJson a nullable list List<T>? or your return from getHeroes() a non-nullable list List

Be careful making your List nullable or non-nullable List<Hero>?, not your Hero List<Hero?>

  • Related