I try to create a List of functions in Dart, but am unable to use the List add method for this. This is the code, and it is all in the same file.
// bin/filter.dart
import 'package:filter/filter.dart';
import 'package:filter/LogEntry.dart';
void main(List<String> arguments) {
LogEntry log = new LogEntry();
TripListFilter filter = new TripListFilter(true);
for (FilterFunction f in filter.filters) {
print('Filter: ${f(log)}');
}
}
// lib/LogEntry.dart
class LogEntry {
bool trailer = false;
}
// lib/filter.dart
import 'package:filter/LogEntry.dart';
typedef FilterFunction = bool Function(LogEntry a);
class TripListFilter {
TripListFilter(this.trailer);
bool? trailer;
bool _myFunction(LogEntry trip) {
if (trailer == true && trip.trailer) return true;
return false;
}
List<FilterFunction> filters = [];
filters.add(_myFunction);
}
Running this give me the error
Building package executable...
Failed to build filter:filter:
lib/filter.dart:17:3: Error: The name of a constructor must match the name of the enclosing class.
filters.add(_myFunction);
In Android Studio with the Flutter and Dart plugins, I get a red line over the filters
variable in the last line. Hovering above it, I see a message "The name of a constructor must match the name of the enclosing class."
As far as I can see, the definition of the "filters" list matches the signature of _myFunction.
How come the function can not be added to the list?
The problem is that this line
filters.add(_myFunction);
Is outside the body of a function or constructor, which then makes it a declaration. You could add it to the constructor for example like this:
class TripListFilter {
TripListFilter(this.trailer){
filters.add(_myFunction);
}
bool? trailer;
bool _myFunction(LogEntry trip) {
if (trailer == true && trip.trailer) return true;
return false;
}
List<FilterFunction> filters = [];
}
or as pskink suggested initialize the filters with _myFunction
already in it using late
late List<FilterFunction> filters = [_myFunction];
Using late
makes you able to use other class variables in the declaration because it is then lazily initialized, meaning that the list is initialized at the first time you access it.