Problem
When working with an old version of Flutter and using the @required annotation, you may fall into this error:
Undefined name 'required' used as an annotation
More information:
Error: Getter not found: 'required'.
^^^^^^^^
Error: This can't be used as metadata; metadata should be a reference to a compile-time constant variable, or a call to a constant constructor.
Solutions
You can fix the mentioned error in either of the following two ways.
Using the required keyword instead of the @required annotation
In order to use the required keyword, you need to upgrade Flutter to a null-safety version. If you don’t know how to do so, see this article: How to upgrade Flutter SDK and package dependencies. To check your Flutter and Dart versions, see How to check your Flutter and Dart versions.
After having Flutter upgraded, you can rewrite the User class above like this:
class User {
final String id;
final String name;
final String address;
User({
required this.id,
required this.name,
required this.address
})
}
Importing the necessary package
Important: Only use this approach in old versions of Flutter (before null-safety), where you cannot upgrade your project to a newer version of Flutter.
The solution is quite simple. Everything you need to do is to import either the foundation library or the material library:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
Example
import 'package:flutter/material.dart';
class User {
final String id;
final String name;
final String address;
User({
@required this.id,
@required this.name,
@required this.address
})
}
Further reading:
- Dart: Find List Elements that Satisfy Conditions
- Prevent VS Code from Auto Formatting Flutter/Dart Code
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- Using Chip widget in Flutter: Tutorial & Examples
- Create a Custom NumPad (Number Keyboard) in Flutter
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.