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?
2
Answers
The problem is that this line
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:
or as pskink suggested initialize the filters with
_myFunction
already in it usinglate
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.The accepted answer by Ivo more than answers this question. It is worth pointing out, however, that a syntax error of the type:
causing the error:
might be encountered in many circumstances especially by programmers used to Python and new to Dart and Flutter.
As discussed here, it might be useful to have a canonical Q&A that addresses this issue, so that similar questions can be dealt with more efficiently.