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
To cast List to List, you can use the map function to convert each TenancyEntity to Tenancy
As you can a method
toTenancy
inTenancyEntry
to to convert the same toTenancy
, you can usemap
method to solve this.