Home > Blockchain >  String is not subtype of int of index
String is not subtype of int of index

Time:04-24

In this part of code sellers are collected from server as json.

But there is a problem that says

"type 'String' is not a subtype of type 'int' of 'index'"

     Future<List<Seller>> getSellers() async{
    try {
      List<Seller> sellers = [];

      http.Response response = await http.get(Uri.parse('$_baseUrl/gen/sellers.php'),
      
      );
      dynamic jasonobj = jsonDecode(jsonEncode(response.body));
      List sellersList =jasonobj['sellers'];
      for (Map m in sellersList) {
        sellers.add(Seller.fromaMap(m));
      }
      return sellers;
    } catch (e) {
      print('Server error : '   e.toString());
      rethrow;
    }
  }
}

Seller class

class Seller {
  int? id;
  String? name;
  String? email;
  String? image;
  String? address;
  String? description;
  Seller.fromaMap(Map<dynamic, dynamic> map) {
    id = int.parse(map['id']);
    name = map['name'];
    email = map['email'];
    image = map['image'];
    address = map['address'];
    description = map['description'];
  }
}

How can I fix this? thanks for your supports.

CodePudding user response:

id = int.parse(map['id'].toString());

Try the code above. Dynamic types can cause this type of errors.

CodePudding user response:

Code is fine but you have to try like this

Future<List<Seller>> getSellers() async{
try {
List<Seller> sellers = [];
http.Response response = await http.get(Uri.parse('$_baseUrl/gen/sellers.php'),
);
// dynamic jasonobj = jsonDecode(jsonEncode(response.body));
// List sellersList =jasonobj['sellers'];
// for (Map m in sellersList) {
//   sellers.add(Seller.fromaMap(m));
// }
return Seller.jsonToSellerList(jsonDecode(jsonEncode(response.body)) 
["sellers"]);
} catch (e) {
print('Server error : '   e.toString());
rethrow;
}
}
}
class Seller {
int? id;
String? name;
String? email;
String? image;
String? address;
String? description;
Seller.fromaMap(Map<dynamic, dynamic> map) {
id = int.parse(map['id']);
name = map['name'];
email = map['email'];
image = map['image'];
address = map['address'];
description = map['description'];
}
static List<Seller> jsonToSellerList(List<dynamic> sellers) =>
sellers.map<Seller>((item) => Seller.fromaMap(item)).toList();
}

And share base URL that will help to understand the GET API Response

CodePudding user response:

"type 'String' is not a subtype of type 'int' of 'index'"

The problem is in this line, check your api structure and make sure you're accessing the list correctly.

List sellersList =jasonobj['sellers'];

I'm assuming the response is a list of map and then you should access it like this

List sellersList =jasonobj[0]['sellers'];
  • Related