为什么某些变量在flutter自定义类中被标记为final?

前端之家收集整理的这篇文章主要介绍了为什么某些变量在flutter自定义类中被标记为final?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在网上的一些例子中注意到,扩展StatefulWidget的类具有标记为final的实例变量.这是为什么 ?
我理解final关键字的作用.我不明白为什么用扩展widget类的每个实例变量声明它.

解决方法

因为StatefulWidget继承了标记为@immutable的Widget,所以StatefulWidget的任何子类也必须是不可变的(即所有字段都是final).

如果使用非final字段创建StatefulWidget子类,则会产生此DartAnalysis警告:

info: This class inherits from a class marked as @immutable,and
therefore should be immutable (all instance fields must be final).
(must_be_immutable at […] lib….dart:23)

并解释如何使用StatefulWidget documentation中的StatefulWidget:

StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method,or in objects to which that State subscribes,for example Stream or ChangeNotifier objects,to which references are stored in final fields on the StatefulWidget itself.

猜你在找的Flutter相关文章