Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter/getx how to initialize nullable obejct observable

let's say I have a controller like this:

class ProfileController extends GetxController {
  Rx<UserFacebookInfo?>  facebookInfo = null.obs;

  void facebookSync() async {
    //
    // logic to get user info from facebook
    //

    facebookInfo.value = UserFacebookInfo.fromFacebookApi(userData);
    // facebookInfo = UserFacebookInfo.fromFacebookApi(userData).obs;  <=== also tried this
      update();
    }
  }
}

and in widget I have something like this:

Widget buildFacebook() =>  Padding(
      padding: const EdgeInsets.only(top: 30.0, right: 20.0, left: 20.0, bottom: 10.0),
      child: Obx(() => (_profileController.facebookInfo.value == null)  ? Column(
        children:  [
        IconButton(
          icon : const Icon(Icons.facebook_outlined, size: 40.0),
          onPressed: () => _profileController.facebookSync()
        ),
          const Text(
            'Facebook',
            style: TextStyle(color: Colors.white),
          )
        ],
      ) :
      Column(
        children: [
          UserProfileAvatar(
            avatarUrl: _profileController.facebookInfo.value!.facebookAvatar,
            radius: 40,
          ),
          Text(
            _profileController.facebookInfo.value!.name,
          style: const TextStyle(color: Colors.white),
          )
        ],
      )
  ));

and because initial value nullable, it's not working and not changing widget on a fly, but only if I update it from android studio. What is the correct way to initialize it??? I had similar case with nullable string observable so I was able to initialize it lie String string (null as String?).obs` Thanks for any advice

like image 511
Bogdan Dubyk Avatar asked Feb 01 '26 02:02

Bogdan Dubyk


1 Answers

You can initialize nullable observables by using Rxn<Type>().

Therefore use this:

 final facebookInfo= Rxn<UserFacebookInfo>();
like image 101
S. M. JAHANGIR Avatar answered Feb 02 '26 22:02

S. M. JAHANGIR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!