为什么我需要在初始化时转换 Rx 对象的值?
考虑这段代码:
Rx<Widget> rxwidget = const Text("test").obs;
rxwidget.value = Container();
这将在运行时抛出以下错误
Expected a value of type 'Text', but got one of type 'Container'
这对我来说似乎非常不合逻辑,因为该变量只要求它是一个Widget
,而两者都是。它以某种方式将类型限制为它获得的第一个值。 但如果我这样写:
Rx<Widget> rxwidget = (const Text("test") as Widget).obs;
rxwidget.value = Container();
它工作正常,但 IDE(Android Studio)实际上抱怨强制转换是不必要的。
请注意,删除 const
关键字没有帮助。
另一个例子
Rx<String?> test = null.obs;
test.value = "test";
我很确定
Expected a value of type 'Null', but got one of type 'String'
它曾经有效,所以我怀疑这是颤振的最近变化。
这可能是 flutter/dart 中的错误吗?或者说这是为什么呢?
版本信息:
Flutter 2.10.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7e9793dee1 (2 weeks ago) • 2022-03-02 11:23:12 -0600
Engine • revision bd539267b4
Tools • Dart 2.16.1 • DevTools 2.9.2
Consider this code:
Rx<Widget> rxwidget = const Text("test").obs;
rxwidget.value = Container();
This will throw the following error on runtime
Expected a value of type 'Text', but got one of type 'Container'
This seems very illogical to me because the variable only requires it to be a Widget
which both are. It somehow restricts the type to the first value it gets.
But if I write it like this:
Rx<Widget> rxwidget = (const Text("test") as Widget).obs;
rxwidget.value = Container();
It works fine, but the IDE (Android Studio) actually complains that the cast is unnecessary.
Note, removing the const
keyword doesn't help.
Another example
Rx<String?> test = null.obs;
test.value = "test";
giving
Expected a value of type 'Null', but got one of type 'String'
I'm pretty sure it used to work, so I suspect it's a recent change in flutter.
Is this maybe an error in flutter/dart? Or why is this?
version info:
Flutter 2.10.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7e9793dee1 (2 weeks ago) • 2022-03-02 11:23:12 -0600
Engine • revision bd539267b4
Tools • Dart 2.16.1 • DevTools 2.9.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
所以
(const Text("test")).obs
的类型为Rx
->错误的解决方案
Because of
So
(const Text("test")).obs
has typeRx<Text>
-> wrongSolution