When I annotate a constructor parameter with @required
IntelliJ shows an error:
Annotation must be either a const variable reference or const constructor invocation
Can anyone suggest what I'm doing wrong?
class StatusBar extends StatelessWidget { final String text; const StatusBar({Key key, @required this.text}) : assert(text != null), super(key: key); @override Widget build(BuildContext context) { //... } }
@required is an annotation that will create a warning for you to remember that the named parameter is necessary for the class to work as expected.
How does @required compare to the new required keyword? The @required annotation marks named arguments that must be passed; if not, the analyzer reports a hint. With null safety, a named argument with a non-nullable type must either have a default or be marked with the new required keyword.
The @required annotation indicates that the parameter is a required parameter (i.e an argument needs to be passed to the parameter). You can instead create the function parameters without using the optional parameter syntax which implicitly makes it a required.
Unlike positional parameters, the parameters' name must be specified while the value is being passed. Curly brace {} can be used to specify optional named parameters.
Annotations need to be imported
Adding at the top of your file
import 'package:flutter/foundation.dart';
should fix it.
Annotations the DartAnalyzer understands are provided by the meta package.
To make it easier for Flutter developers, the Flutter team decided to add the meta
package to the Flutter SDK and re-export it in flutter/foundation.dart
. The annotations by flutter are therefore exactly the same as these provided by the meta package and you can as well add meta
to your dependencies in pubspec.yaml
and import annotations from there if you prefer. If you want to reuse code between for example AngularDart and Flutter that is the preferred way because code that imports from package:flutter/...
can't be used in Dart web applications.
Please import package "meta" at the beginning of the source file.
// @required is defined in the meta.dart package import 'package:meta/meta.dart';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With