英文:
Cast list object to another list object
问题
将 List<TenancyEntity>
转换为 List<Tenancy>
可以使用以下代码:
var a = await _tenancyLocalDataSource.getTenancyList();
var b = a!.map((entity) => entity.toTenancy()).toList();
debugPrint(b.toString());
这会将 TenancyEntity
对象列表转换为 Tenancy
对象列表,通过调用 toTenancy()
方法来实现。这样可以避免类型转换异常。
英文:
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
答案1
得分: 2
要将List<TenancyEntity>转换为List<Tenancy>,您可以使用map函数将每个TenancyEntity转换为Tenancy
List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => Tenancy.fromEntity(entity)).toList();
debugPrint(b.toString());
英文:
To cast List<TenancyEntity> to List<Tenancy>, 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());
答案2
得分: 0
你可以在TenancyEntry
中添加一个名为toTenancy
的方法,用于将其转换为Tenancy
,你可以使用map
方法来解决这个问题。
List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => entity.toTenancy()).toList();
debugPrint(b.toString());
英文:
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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论