为什么我需要在初始化时转换 Rx 对象的值?

发布于 2025-01-15 03:58:56 字数 1044 浏览 1 评论 0原文

考虑这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尛丟丟 2025-01-22 03:58:56

因为

Rx<T> get obs => Rx<T>(this);

所以 (const Text("test")).obs 的类型为 Rx ->错误的

解决方案

final rxwidget = Rx<Widget>(const Text("test"));

Because of

Rx<T> get obs => Rx<T>(this);

So (const Text("test")).obs has type Rx<Text> -> wrong

Solution

final rxwidget = Rx<Widget>(const Text("test"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文