'Flutter how to cast the model object to another model to save it to HIVE

I have an API response and parsed it using ProductsModel and I am trying to save it to my local storage using Hive and I have different model called LocalProductsModel. How can I cast the response ProductsModel to LocalProductsModel? I used product.cast<LocalProductsModel>();

Here's my Products Model:

  class ProductsList{
      final List<ProductsModel> products;
      ProductsList({this.products});
      factory ProductsList.fromJSON(List<dynamic> parsedJson){
        List <ProductsModel> productsList = new List<ProductsModel>();
        productsList = parsedJson.map((i) => ProductsModel.fromJSON(i)).toList();
        return new ProductsList(
          products: productsList
        );
      }
    }
    class ProductsModel {
      final int id;
      final String name;
      final String catalog_visibility;
      final String description;
      final String short_description;
      final String price;
      final String regular_price;
      final String sale_price;
      final String date_created;

      final List<CategoriesModel> categories;
      final List<ImagesModel> images;
      ProductsModel(
          {this.id,
          this.name,
          this.catalog_visibility,
          this.description,
          this.short_description,
          this.price,
          this.regular_price,
          this.sale_price,
          this.date_created,
          this.categories,
          this.images
          });

      factory ProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
        var categoriesList = parsedJson['categories'] as List;
        var imagesList = parsedJson['images'] as List;
        List<ImagesModel> dataImages = imagesList.map((i) => ImagesModel.fromJSON(i)).toList();
        List<CategoriesModel> dataCategories =
        categoriesList.map((i) => CategoriesModel.fromJSON(i)).toList();
        return ProductsModel(
          id: parsedJson['id'],
          name: parsedJson['name'],
            catalog_visibility: parsedJson['catalog_visibility'],
            description: parsedJson['description'],
            short_description: parsedJson['short_description'],
            regular_price: parsedJson['regular_price'],
            sale_price: parsedJson['sale_price'],
            date_created: parsedJson['date_created'],
            categories: dataCategories,
          images: dataImages
        );

      }

      Map<String, dynamic> toMap() {

        var map = new Map<String, dynamic>();
        ImagesModel img = ImagesModel();
        map["id"] = id;
        map["name"] = name;
        map["description"] = description;
        map["catalog_visibility"] = catalog_visibility;
        map["short_description"] = short_description;
        map["regular_price"] = regular_price;
        map["sale_price"] = sale_price;
        map["date_created"] = date_created;
        map['images'] = this.images.map((v) => v.toMap()).toList();
        return map;
      }
    }

    class CategoriesModel {
      final int id;
      final String name;

      CategoriesModel({this.id, this.name});
      factory CategoriesModel.fromJSON(Map<String, dynamic> parsedJson) {
        return CategoriesModel(id: parsedJson['id'], name: parsedJson['name']);
      }

      Map<String, dynamic> toMap() {

        var map = new Map<String, dynamic>();
        map["id"] = id;
        map["name"] = name;
        return map;
      }
    }

    class ImagesModel{
      final int id;
      final String src;
      final String name;

      ImagesModel({this.id, this.src, this.name});
      factory ImagesModel.fromJSON(Map<String, dynamic> parsedJson){
        return ImagesModel(
          id: parsedJson['id'],
          src: parsedJson['src'],
          name: parsedJson['name']
        );
      }
      Map<String, dynamic> toMap() => {
        "id": id,
        "src": src,
        "name" :name,
      };
    }

My LocalProductModel for my hive local storage:

import 'package:hive/hive.dart';
part 'localProducts.g.dart';


@HiveType(typeId: 0)
class LocalProductsModel {
  @HiveField(0)
  final int id;

  @HiveField(1)
  final String name;

  @HiveField(2)
  final String catalog_visibility;

  @HiveField(3)
  final String description;

  @HiveField(4)
  final String short_description;

  @HiveField(5)
  final String price;

  @HiveField(6)
  final String regular_price;

  @HiveField(7)
  final String sale_price;

  @HiveField(8)
  final String date_created;

  @HiveField(9)
  final List<LocalCategoriesModel> categories;

  @HiveField(10)
  final List<LocalImagesModel> images;
  LocalProductsModel(
      {this.id,
        this.name,
        this.catalog_visibility,
        this.description,
        this.short_description,
        this.price,
        this.regular_price,
        this.sale_price,
        this.date_created,
        this.categories,
        this.images
      });

  factory LocalProductsModel.fromJSON(Map<String, dynamic> parsedJson) {
    var categoriesList = parsedJson['categories'] as List;
    var imagesList = parsedJson['images'] as List;
    List<LocalImagesModel> dataImages = imagesList.map((i) => LocalImagesModel.fromJSON(i)).toList();
    List<LocalCategoriesModel> dataCategories =
    categoriesList.map((i) => LocalCategoriesModel.fromJSON(i)).toList();
    return LocalProductsModel(
        id: parsedJson['id'],
        name: parsedJson['name'],
        catalog_visibility: parsedJson['catalog_visibility'],
        description: parsedJson['description'],
        short_description: parsedJson['short_description'],
        regular_price: parsedJson['regular_price'],
        sale_price: parsedJson['sale_price'],
        date_created: parsedJson['date_created'],
        categories: dataCategories,
        images: dataImages
    );

  }

  Map<String,dynamic> toMap() {

    var map = new Map<String, dynamic>();
    LocalImagesModel img = LocalImagesModel();
    Map<String,dynamic> images = img.toMap();
    map["id"] = id;
    map["name"] = name;
    map["description"] = description;
    map["catalog_visibility"] = catalog_visibility;
    map["short_description"] = short_description;
    map["regular_price"] = regular_price;
    map["sale_price"] = sale_price;
    map["date_created"] = date_created;
    map['images'] = this.images.map((v) => v.toMap()).toList();
    return map;
  }
}

class LocalCategoriesModel {
  final int id;
  final String name;

  LocalCategoriesModel({this.id, this.name});
  factory LocalCategoriesModel.fromJSON(Map<String, dynamic> parsedJson) {
    return LocalCategoriesModel(id: parsedJson['id'], name: parsedJson['name']);
  }

  Map<String,dynamic> toMap() {

    var map = new Map<String, dynamic>();
    map["id"] = id;
    map["name"] = name;
    return map;
  }
}

class LocalImagesModel{
  final int id;
  final String src;
  final String name;

  LocalImagesModel({this.id,this.src,this.name});
  factory LocalImagesModel.fromJSON(Map<String,dynamic> parsedJson){
    return LocalImagesModel(
        id: parsedJson['id'],
        src: parsedJson['src'],
        name: parsedJson['name']
    );
  }
  Map<String, dynamic> toMap() => {
    "id": id,
    "src": src,
    "name" :name,
  };
}

I have a working add function on hive but I know this is wrong cause I didn't cast it to my LocalProductsModel:

postCartLocal(ProductsModel products){

     Map<String, dynamic> productsMap = products.toMap();
    Hive.box('cart').add(productsMap);
  }

When I am getting the value I got an error type

'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'LocalProductsModel' in type cast

My Code on getting the value on local storage:

 Widget _buildListView(){
    return ValueListenableBuilder(
      valueListenable: Hive.box('cart').listenable(),
      builder: (context, snapshot, widget){
        return ListView.builder(
          itemCount: snapshot.length,
            itemBuilder: (context, index) {
            final cart = snapshot.getAt(index) as LocalProductsModel;

            print('lenght ${cart.name}');

            });
      }
    );
  }


Solution 1:[1]

This should work:

final cart = snapshot.getAt(index).cast<LocalProductsModel>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehedi Hasan