Search code examples
annotationswidgetflutter

How to use @required annotation on Flutter constructor parameters?


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) {
    //...
  }
}

Solution

  • 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.