如何 return 并在工厂构造函数中保留空值?

How to return and persist the null in a factory constructor?

我在迁移到 null-safety 时遇到问题,我知道在工厂中它不应该再 return null 所以我 return throw ArgumentError(""),但是在我的服务中,我将 canvas 的值作为 null ,这就是它发送错误的地方,但是我想要的是继续应用程序并将该值保留为 null.

为了更好地解释它;我有两个模型,ModelA 有一个名为 canva 的变量,类型为 ModelB。当我从服务器向 ModelA 发送数据映射时,变量 canva 到达 null,因此它进入一个条件并给出一个错误。

模型A:

class ModelA extends A {
   ModelA ({
       required ModelB? background,
       required ModelB? canvas,
     }) : super(
            background,
            canvas,
   );

    factory ModelA.fromMap(Map<String, dynamic>? map) {
        if (map == null) throw ArgumentError('ModelA map must not be null');
    
        return ModelA(
           background: ModelB.fromMap(map['background']), // go in with not-null service value
           canvas: ModelB.fromMap(map['canvas']), // go in with null service value
        );
      }
}

模型B:

class ModelB extends B {
    ModelB({
        String? content,
      }) : super(
              content;
            );


    factory ModelB.fromMap(Map<String, dynamic>? map) {
        // * before the migration null-safety
        // if (map == null) return null
        if (map == null) throw ArgumentError('ModelB map must not be null'); // enter here (error)
    
        return ModelB(
          content: map['content'],
        );
      }
}

错误后,我进入我的应用程序没有任何问题,但它不再运行我的功能...

这是我进行编程以保存和 return 我完整的 ModelA

final someList = List<ModelA>.from(
        listFromServer.where((i) {
          return (i['someType'] == 1));
        }).map(
          (i) {
            print("enter here");
            final isBackOrCan = i['background'] ?? i['canvas'];
            if (isBackOrCan != null) {
              newListModelB
                  .add(ModelB.fromMap(isBackOrCan));
            }
            return ModelA.fromMap(i); // enter here the map background not null and also the canva null
          },
        ),
      );

[ ... more code that i want to continue ...]

} catch (e) {
      print(e); // the message
      throw CacheException();
}

错误:

如果您想保留返回 null 的旧行为,只需使用 static 方法而不是 factory 构造函数。 (factory constructors provide almost no advantages to static methods anyway.)这将是最简单、最直接的修复方法。

但是如果你真的想禁止 null,那么 ModelA.fromMapModelB.fromMap 应该首先要求 map 是不可空的,然后你将需要继续调用链以使调用者检查 null 值。在你的情况下:

class ModelA extends A {
  ModelA({
    required ModelB? background,
    required ModelB? canvas,
  }) : super(
          background,
          canvas,
        );

  factory ModelA.fromMap(Map<String, dynamic> map) {
    var background = map['background'];
    var canvas = map['canvas'];
    return ModelA(
      background: background == null
          ? null
          : ModelB.fromMap(background), // go in with not-null service value
      canvas: canvas == null
          ? null
          : ModelB.fromMap(canvas), // go in with null service value
    );
  }
}