'Null' 不能分配给参数类型 'AccountType Function()'

时间:2021-04-01 20:08:03

标签: dart flutter-test dartz

有些人可能会向我解释这里发生了什么。我对 flutter 和 dart 编程完全陌生,我已经在 youtube 上开始了一个使用 DDD 架构的视频教程,但我猜该教程没有使用带有 null safety 功能的新版本的 flutter,我猜可以考试未通过的原因。我只是按照教程中的那样做,唯一的区别是类名和 flutter 和 dart 版本。

测试输出 The argument type 'Null' can't be assigned to the parameter type 'AccountType Function()'.

代码

import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:matcher/matcher.dart' as matcher;

void main() {
  group('AccountType', () {
    test('Should return Failure when the value is empty', () {
      // arrange
      var accountType = AccountType.create('')
          .fold((err) => err, (accountType) => accountType);
      // assert
      expect(accountType, matcher.TypeMatcher<Failure>());
    });

    test('Should create accountType when value is not empty', () {
      // arrange
      String str = 'sender';
      AccountType accountType = AccountType.create(str).getOrElse(null); <--- Here where the test fails.
      // assert
      expect(accountType.value, 'sender');
    });
  });
}

class AccountType extends Equatable {
  final String? value;

  AccountType._(this.value);

  static Either<Failure, AccountType> create(String? value) {
    if (value!.isEmpty) {
      return Left(Failure('Account type can not be empty'));
    } else {
      return Right(AccountType._(value));
    }
  }

  @override
  List<Object?> get props => [value];
}

class Failure {
  final String? message;

  Failure(this.message);
}

1 个答案:

答案 0 :(得分:0)

有了空安全,你真的不需要使用 getOrElse 或两个单独的函数 相反,您可以通过添加 ?给它

String? str = 'sender';
  AccountType accountType = AccountType.create(str)

在你的函数内部,我们可以使用空安全来检查它并在函数内适当地处理它

static Either<Failure, AccountType> create(String? value) {
if (value?.isEmpty) {
  return Left(Failure('Account type can not be empty'));
} else {
  return Right(AccountType._(value));
}

}

value?.isEmpty

等于

if(value != null && value.isEmpty) { return value.isEmpty } else { return null)

我们可以使用 ??

来检查它是否为空
value?.isEmpty ?? true

这意味着

if(isEmpty != null) { return isEmpty } else { return true }