How to solve This class inherits from a class marked as @immutable, and therefore should be immutable

- Andrés Cruz

En español

The warning:

This class inherits from a class marked as @immutable, and therefore should be immutable 

It appears on our classes of type StatelessWidget or StatefullWidget in Dart with Flutter that do not have their properties defined as final that is the values must be of immutable type Immutability is a topic that we developers handle when creating applications but it is essential to handle it correctly for the following reasons:

  • Immutability is essential in creating robust and predictable applications.
  • Immutability is essential to ensure stability and prevent errors in the handling of application state.

A class like the following:

class MyApp extends StatelessWidget {
 UserPreference userPreference = UserPreference();
 MyApp({super.key});

The UserPreference property must be final:

class MyApp extends StatelessWidget {
 final UserPreference userPreference = UserPreference();
 MyApp({super.key});

With this, the previous error will disappear.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.