flutter开发警告This class (or a class that this class inherits from) is marked as ‘@immutable‘, but one

Insert image description here

Problem Description

This class (or a class that this class inherits from) is marked as ‘@immutable’, but one or more of its instance fields aren’t final: SerialsTimer.tasks
Insert image description here

problem code

class SerialsTimer extends StatefulWidget {
    
    
  late Queue <Task> tasks; // 使用 Queue 来管理任务

  SerialsTimer({
    
    
    Key? key,
    required this.tasks,
  }) : super(key: key);

  
  State<SerialsTimer> createState() => _SerialsTimerState();
}

problem causes

Dart infers that the class you wrote is an @immutable (immutable) class.
This warning is because in a class marked as @immutable (immutable), one of the instance fields (member variables) is not declared as final.

In Dart, if you use the @immutable annotation, it requires that all instance fields of the class should be final to ensure the immutability of the object. The creation and management of immutable objects helps write more reliable and maintainable code.

How to solve

To resolve this warning, you can mark instance fields as final when declaring them.

Added final modifier to fix tasks field in SerialsTimer class. In this way, the class meets the requirements of @immutable. Please make sure to comply with the regulations in other fields as well.

Modified source code

class SerialsTimer extends StatefulWidget {
    
    
  final Queue <Task> tasks; // 使用 Queue 来管理任务

  const SerialsTimer({
    
    
    Key? key,
    required this.tasks,
  }) : super(key: key);

  
  State<SerialsTimer> createState() => _SerialsTimerState();
}

Insert image description here


Conclusion
Flutter is an open source UI toolkit developed by Google that allows you to create high-quality, beautiful applications on different platforms without writing a lot of platform-specific code. I will learn and delve into all aspects of Flutter. From basic knowledge to advanced techniques, from UI design to performance optimization, join us to discuss and learn together, and enter the wonderful world of Flutter together!

Guess you like

Origin blog.csdn.net/yikezhuixun/article/details/134826156