Home > Blockchain >  Why do I need to cast the value of the Rx object on initialization?
Why do I need to cast the value of the Rx object on initialization?

Time:03-18

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

CodePudding user response:

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"));
  • Related