我注意到在网上的一些示例中,扩展 StatefulWidget
的类具有用 final 标记的实例变量。这是为什么?
我了解 final 关键字的作用。我不明白为什么要使用扩展小部件类的每个实例变量来声明它。
最佳答案
因为StatefulWidget
继承了Widget
,标记为@immutable
,所以StatefulWidget
的任何子类也必须是不可变(即所有字段最终)。
如果你创建一个带有非最终字段的 StatefulWidget
子类,它会导致这个 Dart 分析警告:
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
的说明来自 StatefulWidget documentation :
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.
https://stackoverflow.com/questions/50108234/
相关文章:
android - flutter 的 Image.network 无法在发布 apk 上运行
flutter - 如何在 Flutter 中调整 IconButton 的大小(高度和宽度)
flutter - 在 Flutter 应用中立即显示应用主题
flutter - Flutter ListView、SliverList 等中的当前滚动偏移量
dart - 使用 Flutter/Dart 关闭 Dismissible
flutter - 如何处理在 flutter 中动态创建的复选框列表?
android - 如何在 Flutter 中为文本创建气泡? (WhatsApp 用户界面)