将列表对象转换为另一个列表对象。

huangapple go评论57阅读模式
英文:

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&lt;TenancyEntity&gt; a = await _tenancyLocalDataSource.getTenancyList();
List&lt;Tenancy&gt; b = a.map((entity) =&gt; 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&lt;TenancyEntity&gt; a = await _tenancyLocalDataSource.getTenancyList();
List&lt;Tenancy&gt; b = a.map((entity) =&gt; 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&lt;TenancyEntity&gt; a = await _tenancyLocalDataSource.getTenancyList();
List&lt;Tenancy&gt; b = a.map((entity) =&gt; entity.toTenancy()).toList();
debugPrint(b.toString());

huangapple
  • 本文由 发表于 2023年2月18日 17:38:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定