flutter 将列表对象强制转换为其他列表对象

ibps3vxo  于 2023-02-20  发布在  Flutter
关注(0)|答案(2)|浏览(270)

如何将List<TenancyEntity>转换为List<Tenancy>
我使用了以下代码,但出现异常

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

以下是这两个类

    • 租赁实体**
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
    );
  }
}
    • 租赁**
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;
}
    • 错误**
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

忽略此行

zf2sa74q

zf2sa74q1#

要将List强制转换为List,可以使用map函数将每个TenancyEntity转换为Tenancy

List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => Tenancy.fromEntity(entity)).toList();
debugPrint(b.toString());
3htmauhk

3htmauhk2#

由于您可以使用TenancyEntry中的toTenancy方法将其转换为Tenancy,因此您可以使用map方法解决此问题。

List<TenancyEntity> a = await _tenancyLocalDataSource.getTenancyList();
List<Tenancy> b = a.map((entity) => entity.toTenancy()).toList();
debugPrint(b.toString());

相关问题