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

在这里插入图片描述

问题描述

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
在这里插入图片描述

问题代码

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

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

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

问题原因

Dart推断出你写的这个类是一个@immutable(不可变)的类。
这个警告是因为在一个被标记为 @immutable(不可变)的类中,其中的某个实例字段(成员变量)没有被声明为 final。

在Dart中,如果你使用了 @immutable 注解,它要求类的所有实例字段都应该是 final 的,以确保对象的不可变性。不可变对象的创建和管理有助于编写更加可靠和可维护的代码。

如何解决

为了解决这个警告,你可以在声明实例字段时将其标记为 final。

添加了 final 修饰符来修复 SerialsTimer 类中的 tasks 字段。这样,该类就符合 @immutable 的要求了。请确保在其他字段也符合相应的规定。

修改后的源码

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

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

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

在这里插入图片描述


结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!

猜你喜欢

转载自blog.csdn.net/yikezhuixun/article/details/134826156
今日推荐