Flutter-使用Freezed软件包进行序列化无法正常工作

时间:2020-07-11 22:03:22

标签: flutter json-serialization

请参阅以下代码

part 'order.g.dart';
part 'order.freezed.dart';
@freezed
abstract class Order with _$Order{
  const factory Order({List<Item> items}) = _Order;
  factory Order.fromJson(Map<String,dynamic> json) => _$OrderFromJson(json);
}

part 'item.freezed.dart';
part 'item.g.dart';

@freezed
abstract class Item with _$Item{
  const factory Item({String name, int amount}) = _Item;
  factory Item.fromJson(Map<String,dynamic> json) => _$ItemFromJson(json);
}

并运行以下

    var order = Order(items: [Item(name:' aSasaS')]);
    print(order.toJson().toString());
    final o = Order.fromJson(order.toJson());
    print('all done');

得到以下异常:

type '_$_Item' is not a subtype of type 'Map<String, dynamic>' in type cast
When the exception was thrown, this was the stack:
#0      _$_$_OrderFromJson.<anonymous closure> 
package:test7/order.g.dart:13
#1      MappedListIterable.elementAt  (dart:_internal/iterable.dart:417:31)
#2      ListIterator.moveNext  (dart:_internal/iterable.dart:343:26)
#3      new List.from  (dart:core-patch/array_patch.dart:38:29)
#4      new List.of  (dart:core-patch/array_patch.dart:68:17)
#5      ListIterable.toList  (dart:_internal/iterable.dart:211:44)

这是否意味着我们不能在@freezed对象中使用像List这样的集合?

0 个答案:

没有答案