I have a class which accept a function as a constructor parameter. I want to define a secondary constructor where the user can provide a static value instead. I did something like this:
import 'package:dartz/dartz.dart';
class UpdateCheckNotWorking {
final Function0<Future<String>> versionProvider;
UpdateCheckNotWorking(this.versionProvider);
UpdateCheckNotWorking.withStaticVersion(String version)
: versionProvider = () => Future.value(version);
}
This code does not compile because of 2 errors:
A workaround is to use a late final
field and initialize it in the constructor body:
class UpdateCheckOk {
late final Function0<Future<String>> versionProvider;
UpdateCheckOk(this.versionProvider);
UpdateCheckOk.withStaticVersion(String version) {
versionProvider = () => Future.value(version);
}
}
But I am wondering, why is the first implementation not valid?
CodePudding user response:
It seems to work if you add some parenthesis:
import 'package:dartz/dartz.dart';
class UpdateCheckOk {
final Function0<Future<String>> versionProvider;
UpdateCheckOk(this.versionProvider);
UpdateCheckOk.withStaticVersion(String version)
: versionProvider = (() => Future.value(version));
}