Home > Mobile >  what is this error type 'String' is not a subtype of type 'int' of 'index&#
what is this error type 'String' is not a subtype of type 'int' of 'index&#

Time:10-25

I'm trying to view data that comes from API with GetX but there is something wrong I tried to fix it but I can't What's the problem guys please

this is my controller:

class ProductController extends GetxController {
  var productsList = <Product>[].obs;
  var isLoading = true.obs;

  @override
  void onInit() {
    fetchProducts();
    super.onInit();
  }

  void fetchProducts() async {
    try {
      var product = await RemoteServices.fetchData();
      if (product != null) {
        productsList.value = product;
        isLoading.value = false;
      }
    } catch (e) {
      print(e);
    }
  }
}

and this is Remote Service:

class RemoteServices {
  static var client = http.Client();

  static Future<List<Product>> fetchData() async {
    final uri = Uri.parse(
        "https://makeup-api.herokuapp.com/api/v1/products.json?product_type=blush");
    final response = await client.get(uri);
    if (response.statusCode == 200) {
      var jsonData = json.decode(response.body);
      final productsListJson =
          (jsonData[''] as List).map((e) => Product.fromJson(e)).toList();
      //jsonData['data']^^^
      print("its WORK SUCCESSFULLY");
      return productsListJson;
    } else {
      throw Exception('Something Wrong :(');
    }
  }
}

and this is View Page :

class HomePage extends StatelessWidget {
  final productController = Get.put(ProductController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.purple,
      body: Obx(() => productController.isLoading.value
          ? Center(
              child: CircularProgressIndicator(),
            )
          : ListView.builder(
              itemCount: productController.productsList.length,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child: Column(
                    children: [
                      Image.network(productController
                          .productsList[index].imageLink
                          .toString()),
                      Text(productController.productsList[index].name
                          .toString()),
                      Text(productController.productsList[index].price
                          .toString()),
                    ],
                  ),
                );
              },
            )),
    );
  }
}

when I run the app The CircularProgressIndicator() still running and the run page tell me :

Syncing files to device Android SDK built for x86...
Restarted application in 4,096ms.
[GETX] Instance "ProductController" has been created
[GETX] Instance "ProductController" has been initialized
I/flutter (28829): type 'String' is not a subtype of type 'int' of 'index'

CodePudding user response:

I checked your code and fixed the issues. Here the code...

RemoteService

class RemoteServices {
  static var client = http.Client();

  static Future<List<Product>> fetchData() async {
    final uri = Uri.parse("https://makeup-api.herokuapp.com/api/v1/products.json?product_type=blush");
    final response = await client.get(uri);
    if (response.statusCode == 200) {
      var jsonData = json.decode(response.body);
      final productsListJson = List<Product>.from(jsonData.map((x) => Product.fromJson(x)));
      print("its WORK SUCCESSFULLY");
      return productsListJson;
    } else {
      throw Exception('Something Wrong :(');
    }
  }
}

Product Model class

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

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

class Product {
  Product({
     this.id,
     this.brand,
     this.name,
     this.price,
     this.priceSign,
     this.currency,
     this.imageLink,
     this.productLink,
     this.websiteLink,
     this.description,
     this.rating,
     this.category,
     this.productType,
     this.tagList,
     this.createdAt,
     this.updatedAt,
     this.productApiUrl,
     this.apiFeaturedImage,
     this.productColors,
  });

  int? id;
  String? brand;
  String? name;
  String? price;
  String? priceSign;
  String? currency;
  String? imageLink;
  String? productLink;
  String? websiteLink;
  String? description;
  double? rating;
  String? category;
  String? productType;
  List<String>? tagList;
  DateTime? createdAt;
  DateTime? updatedAt;
  String? productApiUrl;
  String? apiFeaturedImage;
  List<ProductColor>? productColors;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        brand: json["brand"] == null ? null : json["brand"],
        name: json["name"],
        price: json["price"] == null ? null : json["price"],
        priceSign: json["price_sign"] == null ? null : json["price_sign"],
        currency: json["currency"] == null ? null : json["currency"],
        imageLink: json["image_link"],
        productLink: json["product_link"],
        websiteLink: json["website_link"],
        description: json["description"] == null ? null : json["description"],
        rating: json["rating"] == null ? null : json["rating"].toDouble(),
        category: json["category"] == null ? null : json["category"],
        productType: json["product_type"],
        tagList: List<String>.from(json["tag_list"].map((x) => x)),
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
        productApiUrl: json["product_api_url"],
        apiFeaturedImage: json["api_featured_image"],
        productColors: List<ProductColor>.from(json["product_colors"].map((x) => ProductColor.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "brand": brand == null ? null : brand,
        "name": name,
        "price": price == null ? null : price,
        "price_sign": priceSign == null ? null : priceSign,
        "currency": currency == null ? null : currency,
        "image_link": imageLink,
        "product_link": productLink,
        "website_link": websiteLink,
        "description": description == null ? null : description,
        "rating": rating == null ? null : rating,
        "category": category == null ? null : category,
        "product_type": productType,
        "tag_list": List<dynamic>.from(tagList!.map((x) => x)),
        "created_at": createdAt?.toIso8601String(),
        "updated_at": updatedAt?.toIso8601String(),
        "product_api_url": productApiUrl,
        "api_featured_image": apiFeaturedImage,
        "product_colors": List<dynamic>.from(productColors!.map((x) => x.toJson())),
      };
}

class ProductColor {
  ProductColor({
     this.hexValue,
     this.colourName,
  });

  String? hexValue;
  String? colourName;

  factory ProductColor.fromJson(Map<String, dynamic> json) => ProductColor(
        hexValue: json["hex_value"],
        colourName: json["colour_name"] == null ? null : json["colour_name"],
      );

  Map<String, dynamic> toJson() => {
        "hex_value": hexValue,
        "colour_name": colourName == null ? null : colourName,
      };
}

CodePudding user response:

 final productsListJson =
          (jsonData as List).map((e) => Product.fromJson(e)).toList();
  • Related