0

有可能有人可以向我解释这里发生了什么。我对颤振和飞镖编程完全陌生,我已经在 youtube 上开始了一个使用 DDD 架构的视频教程,但我猜该教程没有使用该null safety功能附带的新版本颤振,并猜测这可能是测试的原因没有通过。我只是按照教程中的方式进行操作,唯一的区别是类名以及颤振和飞镖版本。

测试输出 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);
}
4

1 回答 1

2

使用 null 安全性,您实际上不需要使用 getOrElse 或两个单独的函数相反,您可以通过添加将字符串转换为可为空的字符串?对它

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

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

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)

检查它是否为 null 我们可以使用 ??

value?.isEmpty ?? true

意思是

if(isEmpty != null) { return isEmpty } else { return true }
于 2021-04-03T03:05:58.193 回答