Null safety problem
mudlee opened this issue · comments
mudlee commented
Hello! I wrote a custom validator which I add to a MultiValidator:
class NotNullOrEmptyValidator<T> extends FieldValidator<T> {
NotNullOrEmptyValidator({required String errorText}) : super(errorText);
@override
bool isValid(T value) {
return value != null;
}
}
I use it like:
validators.add(NotNullOrEmptyValidator<File>(errorText: 'Required'));
So basically I just checked if the given file is null or not.
When validation occurs, I get this error back:
type 'Null' is not a subtype of type 'File' of 'value'
When the exception was thrown, this was the stack:
#0 FieldValidator.call (package:form_field_validator/form_field_validator.dart)
#1 MultiValidator.isValid (package:form_field_validator/form_field_validator.dart:170:21)
#2 MultiValidator.call (package:form_field_validator/form_field_validator.dart:180:12)
#3 FormFieldState._validate (package:flutter/src/widgets/form.dart:468:37)
#4 FormFieldState.validate.<anonymous closure> (package:flutter/src/widgets/form.dart:461:7)
I also tried to change my logic and not use File, but just a simple String (path of the file), but still I get the same error, but with this message: type 'Null' is not a subtype of type 'String' of 'value'
mudlee commented
@Milad-Akarie ? :)
Stefan Galler commented
@mudlee Looks like that MultiValidator assumes that your Validator is of type String?
.
So if you use it like NotNullOrEmptyValidator<String?>(errorText: 'Required')
it would work.
class MultiValidator extends FieldValidator<String?> {
final List<FieldValidator> validators;
static String _errorText = '';
MultiValidator(this.validators) : super(_errorText);
@override
bool isValid(value) {
for (FieldValidator validator in validators) {
if (validator.call(value) != null) {
_errorText = validator.errorText;
return false;
}
}
return true;
}
@override
String? call(dynamic value) {
return isValid(value) ? null : _errorText;
}
}