I'm very new to flutter and dart, I'm having trouble with functions, I've already spent too much time here. Any help is appreciated. Thank You
`void main(){
Car myCar = Car(drive:slowDrive);
myCar.drive();
}
class Car{
Car({this.drive});
Function drive;
}
void slowDrive(){
print('Driving Slowly');
}
ERROR: Error compiling to JavaScript: main.dart:32:13: Error: Optional parameter 'drive' should have a default value because its type 'Function' doesn't allow null.
ERROR: Error compiling to JavaScript: main.dart:32:13: Error: Optional parameter 'drive' should have a default value because its type 'Function' doesn't allow null.
'Function' is from 'dart:core'. Car({this.drive}); ^^^^^ Error: Compilation failed.
class Car{
Car({this.drive});
Function drive;
}
The way you wrote it ({}
makes the parameter optional), the value can be null and that's why it is complaining as the function can never be null.
This happens because of the new dart Null Safety feature.
You need to add the final keyword and remove the {}
so that the value can't possibly be null.
class Car{
Car(this.drive);
final Function drive;
}
Or as Peter said, add the required keyword so that it still uses the optional syntax but it is required:
class Car{
Car({required this.drive});
final Function drive;
}
Or add a default function:
class Car{
Car({this.drive = someFunction});
final Function drive;
}