我按照此code lab学习Dart / Flutter。我试图编辑一些源代码以使此代码更好。
class ChatScreenState extends State<ChatScreen> with TickerProviderStateMixin {
final List<ChatMessageView> _chatMessageViewList = <ChatMessageView>[];
final TextEditingController _textController = new TextEditingController();
final AnimationController _chatMessageAnimationController;
bool _isComposing = false;
ChatScreenState() {
_chatMessageAnimationController = new AnimationController(
duration: new Duration(microseconds: 700),
vsync: this,
);
}
...
}
我计划重用AnimationController的实例,因为我必须像创建列表一样创建它。但是,无论如何我都不能使用
this
关键字。我理解了此错误消息,但是我想知道有什么方法可以将this
关键字分配给当前类的最终属性吗?最佳答案
final
在
final AnimationController _chatMessageAnimationController;
和
_chatMessageAnimationController = ...
彼此矛盾。实例字段上的
final
表示只能在对象创建时对其进行初始化。这意味着甚至在构造函数体执行之前。你只能用
this._chatMessageAnimationController
ChatScreenState() : _chatMessageAnimationController = ... {
final AnimationController _chatMessageAnimationController = ...;
为该字段分配值。
不幸的是,由于对象初始化尚未完成,因此这些方法均不允许您引用
this
。
关于dart - 如何在Dart中通过 `this`获取当前的类实例并分配给final属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53817414/