Home > Software design >  Get data from API but getting type 'String' is not a subtype of type 'int' of &#
Get data from API but getting type 'String' is not a subtype of type 'int' of &#

Time:04-09

I am getting data from API but getting error type 'String' is not a subtype of type 'int' of 'index'. When I add data in to the server and after adding when I am receiving data from the server I am getting this error. I am using Listview.builder to get the data from the Api. There are three classes for this task

  1. Inventory (Model)
  2. InventoryService (service class)
  3. InventoryController ( controller class)
  4. UserInventoryScreen (view class)

My Model Class is

class Inventory {
  String? quantity;
  String? description;
  String? fieldname;
  String? originalname;
  String? encoding;
  String? mimetype;
  String? id;
  String? filename;
  Metadata? metadata;
  String? bucketName;
  int? chunkSize;
  int? size;
  String? md5;
  DateTime? uploadDate;
  String? contentType;
  String? url;

  Inventory({
    this.quantity,
    this.description,
    this.fieldname,
    this.originalname,
    this.encoding,
    this.mimetype,
    this.id,
    this.filename,
    this.metadata,
    this.bucketName,
    this.chunkSize,
    this.size,
    this.md5,
    this.uploadDate,
    this.contentType,
    this.url,
  });
  factory Inventory.fromJson(Map<String, dynamic> json) => Inventory(
        quantity: json["quantity"],
        description: json["description"],
        fieldname: json["fieldname"],
        originalname: json["originalname"],
        encoding: json["encoding"],
        mimetype: json["mimetype"],
        id: json["_id"],
        filename: json["filename"],
        metadata: Metadata.fromJson(json["metadata"]),
        bucketName: json["bucketName"],
        chunkSize: json["chunkSize"],
        size: json["size"],
        md5: json["md5"],
        uploadDate: DateTime.parse(json["uploadDate"]),
        contentType: json["contentType"],
        url: json["url"],
      );

  Map<String, dynamic> toJson() => {
        "quantity": quantity,
        "description": description,
        "fieldname": fieldname,
        "originalname": originalname,
        "encoding": encoding,
        "mimetype": mimetype,
        "_id": id,
        "filename": filename,
        "metadata": metadata!.toJson(),
        "bucketName": bucketName,
        "chunkSize": chunkSize,
        "size": size,
        "md5": md5,
        "uploadDate": uploadDate!.toIso8601String(),
        "contentType": contentType,
        "url": url,
      };
}

class Metadata {
  Metadata({
    this.description,
    this.quantity,
    this.url
  });

  String? description;
  String? quantity;
  String? url;

  factory Metadata.fromJson(Map<String, dynamic> json) => Metadata(
        description: json["description"],
        quantity: json["quantity"],
        url: json["url"],
      );

  Map<String, dynamic> toJson() => {
        "description": description,
        "quantity": quantity,
        "url": url
      };
}

My InventoryService class code is

 Future<List<Inventory>> requestInventory(
      String accessToken, String userId) async {
    final response = await http.get(Uri.parse('${AppUrl.getInventory}/$userId'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          'Authorization': 'Barear $accessToken'
        });

    late List<Inventory> list;

  

    if (response.statusCode == 200) {
      var value = jsonDecode(response.body);

     

      var data = value['details']['data']['user']['inventory'];

     

      if (data != null || data != []) {
        list = data.map<Inventory>((json) => Inventory.fromJson(json)).toList();
        
        return list;
      } else {
        return list = [];
      }

     

    } else {
      return list = [];
    }
  }

My InventoryController class code is

Future getMyInvenoryFromService() async {
    try {
   
      isLoadingInventory(true);
      String? userId = await preferenceService.getuserId();
      String? accessToken = await preferenceService.getAccessToken();
      await inventoryService.requestInventory(accessToken!, userId!).then((val) {
     
          inventoryData = val;
         
        }
      );

    } finally {
      isLoadingInventory(false);
    }
  }

And My UserInventoryScreen class code is

import 'package:bartermade/controllers/giftController.dart';
import 'package:bartermade/services/giftStorageService.dart';
import 'package:bartermade/widgets/snackBar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:bartermade/controllers/inventoryController.dart';
import 'package:bartermade/screens/Inventory/addInventory.dart';
import 'package:bartermade/utils/app_colors.dart';

class UserInventoryScreen extends StatefulWidget {
  final String isScreen;
  const UserInventoryScreen({
    Key? key,
    required this.isScreen,
  }) : super(key: key);
  @override
  _UserInventoryScreenState createState() => _UserInventoryScreenState();
}

class _UserInventoryScreenState extends State<UserInventoryScreen> {
  InventoryController inventoryController = Get.put(InventoryController());
  GiftController giftController = Get.put(GiftController());
  GiftStorageService giftStorageService = GiftStorageService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.pinkAppBar,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.transparent,
        leading: InkWell(
            onTap: () {
              Get.back();
            },
            child: Icon(Icons.arrow_back)),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('Inventory'),
            InkWell(
              onTap: () {
                Get.to(AddInventoryScreen());
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration:
                BoxDecoration(border: Border.all(color: Colors.white)),
                child: Text(
                  "Add Inventory",
                  style: TextStyle(fontSize: 16),
                ),
              ),
            )
          ],
        ),
      ),
      body: Container(
          width: double.infinity,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(18),
                topRight: Radius.circular(18),
              )),
          margin: EdgeInsets.only(top: 20),
          padding: EdgeInsets.symmetric(horizontal: 08, vertical: 05),
          child: Obx(() {
            if (inventoryController.isLoadingInventory.value) {
              return Center(child: CircularProgressIndicator());
            } else {
              return ListView.builder(
                  itemCount: inventoryController.myInventoryList.length,
                  itemBuilder: (context, index) {
                    return InkWell(
                      onTap: () async {
                        if (widget.isScreen == 'gift') {
                          var check = await giftStorageService.idExist(
                              inventoryController.myInventoryList[index].id);
                          if (check) {
                            showSnackBar('Gift already exist', context);
                          } else {
                            String id =
                                '${inventoryController.myInventoryList[index].id}';
                            giftStorageService.saveInventoryId(id);
                            giftController.giftList.add(
                                inventoryController.myInventoryList[index]);
                          }
                        }

                        Get.back();
                      },
                      child: Column(
                        children: [
                          Container(
                            decoration: BoxDecoration(
                                border: Border(
                                    bottom: BorderSide(
                                        width: 1, color: Colors.black12))),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 5.0, horizontal: 08),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        height: 100,
                                        width: 200,
                                        decoration: BoxDecoration(
                                            image: DecorationImage(
                                                fit: BoxFit.fitWidth,
                                                image: NetworkImage(
                                                    inventoryController
                                                        .myInventoryList[
                                                    index]
                                                        .url ??
                                                        ""))),
                                      ),
                                      PopupMenuButton(
                                          itemBuilder: (context) => [
                                            PopupMenuItem(
                                              onTap: () {
                                                print(inventoryController
                                                    .myInventoryList[index]
                                                    .id);

                                                var list = inventoryController
                                                    .myInventoryList
                                                    .where((i) =>
                                                i.id !=
                                                    inventoryController
                                                        .myInventoryList[
                                                    index]
                                                        .id)
                                                    .toList();

                                                print('List is => ${list}');

                                                inventoryController
                                                    .deleteInventory(
                                                    list, context);
                                              },
                                              value: 1,
                                              child: Padding(
                                                padding:
                                                const EdgeInsets.all(
                                                    8.0),
                                                child: Text(
                                                  "Delete",
                                                  style: TextStyle(
                                                      color: AppColors
                                                          .pinkAppBar,
                                                      fontWeight:
                                                      FontWeight.w700),
                                                ),
                                              ),
                                            ),
                                          ]),
                                    ],
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      '${inventoryController.myInventoryList[index].description}',
                                      style: TextStyle(
                                        fontSize: 12,
                                      ),
                                      maxLines: 5,
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(right: 15.0),
                                    child: Row(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('',
                                            style: TextStyle(fontSize: 11)),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                          Divider(height: 05),
                        ],
                      ),
                    );
                  });
            }
          })),
    );
  }
}

and my api response is

{
    "details": "got user successfully",
    "data": {
        "user": {
            "role": "user",
            "banned": false,
            "bannedTill": null,
            "inventory": [
                {
                    "quantity": "23",
                    "description": "this is my data",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "This my first inventory ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "this is ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "fvgg",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "dtff",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "2",
                    "description": "this is the description",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hsbsbsnansb",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hbhh",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "htbfnfn",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "My mobile",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "Infinix mobile",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "Infiiiiixxxx Mobile",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": null,
                    "description": "this is the description",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": null,
                    "description": null,
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "Blue Mobile ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "Blue smart mobile",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "Smart mobile ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hello dev",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "bsjsb",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hello",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "mobile",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "helpo ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "desc",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "descc",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hellog",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "check blue",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "this is app inventory ",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "fhbbj",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "yuj",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "hello",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                },
                {
                    "quantity": "0",
                    "description": "ghb",
                    "url": "http://localhost/api/media/inventory-pictures/undefined"
                }
            ],
            "fcmToken": null,
            "profilePictureURL": "https://cdn.luxe.digital/media/2019/09/12090502/business-professional-dress-code-men-style-luxe-digital.jpg",
            "_id": "624bac63fbf73b08462af651",
            "createdAt": "2022-04-05T02:41:39.754Z",
            "updatedAt": "2022-04-09T08:43:16.427Z",
            "firstName": "saad",
            "lastName": "ebad"
        },
        "posts": [
            {
                "tradeWithPictures": [
                    {
                        "publicID": "bartermade/post-pictures/oqzvs8cnioj2yncpembd",
                        "url": "https://res.cloudinary.com/dtksvfjsi/image/upload/v1649202575/bartermade/post-pictures/oqzvs8cnioj2yncpembd.jpg"
                    }
                ],
                "tags": [
                    "Camera",
                    "Mobile",
                    "Cycles"
                ],
                "pictures": [
                    {
                        "publicID": "bartermade/post-pictures/vuepwgaymffwhdvcz3lx",
                        "url": "https://res.cloudinary.com/dtksvfjsi/image/upload/v1649202573/bartermade/post-pictures/vuepwgaymffwhdvcz3lx.jpg"
                    }
                ],
                "comments": [
                    {
                        "text": "bsbsn",
                        "profile": {
                            "role": "user",
                            "banned": false,
                            "bannedTill": null,
                            "inventory": [],
                            "fcmToken": "",
                            "profilePictureURL": "https://cdn.luxe.digital/media/2019/09/12090502/business-professional-dress-code-men-style-luxe-digital.jpg",
                            "_id": "624bac63fbf73b08462af651",
                            "createdAt": "2022-04-05T02:41:39.754Z",
                            "updatedAt": "2022-04-06T04:29:06.535Z",
                            "firstName": "saad",
                            "lastName": "ebad"
                        }
                    }
                ],
                "_id": "624cd591fbf73b08462afb73",
                "title": "Infinix",
                "description": "Infinix note 8",
                "category": "mobiles",
                "subCategory": "smart phones",
                "condition": "Old",
                "user": "624bac63fbf73b08462af651",
                "createdAt": "2022-04-05T23:49:37.116Z",
                "updatedAt": "2022-04-06T04:33:40.069Z"
            }
        ]
    }
}

CodePudding user response:

when fetching data from api why not create our own model and return the data which we get from api to our model.

CodePudding user response:

Can you post your model class and api response

  • Related