Home > Software design >  Flutter getx state is not properly matched when I reactive value
Flutter getx state is not properly matched when I reactive value

Time:05-10

I'm trying to set random network images to flutter app by getX. The problem is when I activate 'nextPhoto', it printed next links in my list. However, image widget didn't change to next photo.

Output example : first photo = cat1.jpg , next photo = cat1.jpg Expected example : first photo = cat1.jpg, next photo = cat2.jpg

Someone helps me will be highly appreciated.

import ...

class ProfileController extends GetxController {
  List<String> imageList = [
    'https://1.jpg'
    'https://2.jpg',
    'https://3.jpg',
    'https://4.jpg',
    'https://5.jpg',
  ];

  late List<String> randomImage = imageList.toList()..shuffle();
  int imageNumber = 0;
  late RxString imagePath = randomImage[imageNumber].obs;
  RxBool isEditMyProfile = false.obs;

  @override
  void onInit() {...}
  void toggleEditProfile() {...}
  void savePhoto() async {...}

  void nextPhoto() {
    print('Next Photo');
    imageNumber != imageList.length ? imageNumber   : imageNumber == 0;
    imagePath = randomImage[imageNumber].obs;
    imageCache.clear();    
    update();
  } 
}
Widget _profileImage() {
    return GestureDetector(
      onTap: () {
        controller.toggleEditProfile();
        print('change my Image!');
      },
      child: Container(
        padding: EdgeInsets.all(10),
        width: Get.mediaQuery.size.width,
        height: Get.mediaQuery.size.height,
        child: FittedBox(
          child: Obx(
            () => Image.network(
              controller.imagePath.value,
              fit: BoxFit.fill,
            ),
          ),
        ),
      ),
    );
  }

CodePudding user response:

Try

Widget _profileImage() {
        return GestureDetector(
          onTap: () {
            controller.nextPhoto();
            print('change my Image!');
          },
          child: Container(
            padding: EdgeInsets.all(10),
            width: Get.mediaQuery.size.width,
            height: Get.mediaQuery.size.height,
            child: FittedBox(
              child: Obx(
                () => Image.network(
                  controller.imagePath.value,
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
        );
      }

or share what's inside toggleEditProfile function.

CodePudding user response:

Save new value insteads of create new obs instance.

ps: look like your randomly imageNumber isn't random actually... nvm

// late RxString imagePath = randomImage[imageNumber].obs;
=> late imagePath = Rx<String>(randomImage[imageNumber]);

// imagePath = randomImage[imageNumber].obs; 
=> imagePath.value = randomImage[imageNumber];
  • Related