skip to Main Content

How can I cast List<TenancyEntity> to List<Tenancy> ?

I use below code but get exception

 var a = await _tenancyLocalDataSource.getTenancyList();
 var b = a!.cast<Tenancy>();
 debugPrint(b.toString());

Below are the both classes

TenancyEntity

import 'package:hive/hive.dart';
import '../../../domain/model/tenancy.dart';

part 'tenancy_entity.g.dart';

@HiveType(typeId: 1)
class TenancyEntity extends HiveObject {
  @HiveField(0)
  int rentalFees;

  TenancyEntity({
    required this.rentalFees,
  });

  Tenancy toTenancy() {
    return Tenancy(
      rentalFees: rentalFees
    );
  }
}

Tenancy

import 'package:equatable/equatable.dart';

class Tenancy extends Equatable {
  final int rentalFees;

  const Tenancy({required this.rentalFees});

  @override
  List<Object?> get props {
    return [rentalFees];
  }

  @override
  bool? get stringify => true;
}

Error

E/flutter ( 6267): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'TenancyEntity' is not a subtype of type 'Tenancy' in type cast

2

Answers


  1. To cast List to List, you can use the map function to convert each TenancyEntity to Tenancy

    List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
    List<Tenancy> b = a.map((entity) => Tenancy.fromEntity(entity)).toList();
    debugPrint(b.toString());
    
    Login or Signup to reply.
  2. As you can a method toTenancy in TenancyEntry to to convert the same to Tenancy, you can use map method to solve this.

    List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
    List<Tenancy> b = a.map((entity) => entity.toTenancy()).toList();
    debugPrint(b.toString());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search