【问题标题】:'Null' can't be assigned to the parameter type 'AccountType Function()''Null' 不能分配给参数类型'AccountType Function()'
【发布时间】:2021-06-28 19:56:16
【问题描述】:

可能有人可以向我解释这里发生了什么。我对颤振和飞镖编程完全陌生,我已经在 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);
}

【问题讨论】:

    标签: dart flutter-test dartz


    【解决方案1】:

    使用 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)
    

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

    value?.isEmpty ?? true
    

    意思是

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

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2021-06-04
      • 1970-01-01
      • 2022-08-05
      • 2022-01-17
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多