33

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) {
    //...
  }
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254

5 Answers5

61

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.

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
30

Please import package "meta" at the beginning of the source file.

// @required is defined in the meta.dart package
import 'package:meta/meta.dart';
madeinQuant
  • 1,721
  • 1
  • 18
  • 29
5

Does your code include the following code?

import 'package:meta/meta.dart';

If your code contains the code above and you get errors, check pubspec.yaml file:

dependencies:
  meta: ^1.4.0
  flutter:
    sdk: flutter

Pay attention to the meta section from the above sample.

If the error persists, try the following on the CLI:

pub upgrade
Alex
  • 5,510
  • 8
  • 35
  • 54
booiljoung
  • 776
  • 6
  • 10
  • Your solution adds new value at all. First, `import 'package:meta/meta.dart';` solution is already provided by someone, second what you have written extra has no meaning when it comes to importing `meta.dart` package because you're not using `meta` in `pubspec.yaml` file. Not sure how you got 2 upvotes. – iDecode May 21 '20 at 08:35
2

I found that this problem can happen if your class has a variable called required

class TextFieldInputWidget extends StatefulWidget {
  final String title;
  final bool required;

  const TextFieldInputWidget({@required this.title, this.required = false});

  @override
  _TextFieldInputWidget createState() => _TextFieldInputWidget();
}

Just change the variable name to something else, like "require"

hook38
  • 3,899
  • 4
  • 32
  • 52
0

If you have null safety enabled, the required keyword is an actual keyword and not a @ notation:

DateTime startDate;
  YourWidget(required this.startDate);
stan
  • 229
  • 3
  • 10