Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading