dartflutter-testdartz

'Null' can't be assigned to the parameter type 'AccountType Function()'


Is possible that some can explain to me what's going on here. I completely new to flutter and dart programming and I have started a video tutorial on youtube which are using DDD architecture, but I guess the tutorial does not use the new version of flutter which comes with the null safety feature and guess that could the reason why the test is not passing. I just did as in the tutorial and the only differences that I have are the class name and flutter and dart version.

Test output The argument type 'Null' can't be assigned to the parameter type 'AccountType Function()'.

code

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);
}

Solution

  • With the null safety you don't really need to use the getOrElse or two separate functions Instead you could just convert your string into a nullable String by adding ? to it

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

    Inside your function we can use null safety to check it and handle it appropriately within the function

    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
    

    is equal to

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

    to check whether or not it's null we can use ??

    value?.isEmpty ?? true
    

    which means

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