Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {     //...   } } 
like image 518
Duncan Jones Avatar asked Apr 17 '18 17:04

Duncan Jones


People also ask

What is @required in flutter?

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

What is the difference between @required and required in flutter?

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.

What is @required in Dart?

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.

How do you make a parameter optional in flutter?

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.


2 Answers

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.

like image 82
Günter Zöchbauer Avatar answered Sep 19 '22 18:09

Günter Zöchbauer


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

// @required is defined in the meta.dart package import 'package:meta/meta.dart'; 
like image 39
madeinQuant Avatar answered Sep 18 '22 18:09

madeinQuant