dart 如何在Getx控制器中使用Observable File变量

4ngedf3f  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(91)

我试图在Getx中使用Observable File变量,但它显示错误。我不知道另一个选项可以在getx中使File可观察。
误差

[Get] the improper use of a GetX has been detected. 
      You should only use GetX or Obx for the specific widget that will be updated.
      If you are seeing this error, you probably did not insert any observable variables into GetX/Obx 
      or insert them outside the scope that GetX considers suitable for an update 
      (example: GetX => HeavyWidget => variableObservable).
      If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX.

字符串
getx控制器代码

File? selectedCoverImage;

   Future pickeCoverImageFromGallery() async {
     final image = await ImagePicker()
         .pickImage(source: ImageSource.gallery, imageQuality: 70);
     if (image == null) return;

       selectedCoverImage = File(image.path);
}


可观测类

Obx(
                    ()=> controller.selectedCoverImage != null
                          ? Image.file(
                              controller.selectedCoverImage!,
                              height: double.infinity,
                              width: double.infinity,
                              fit: BoxFit.cover,
                            )
                          : Image(
                              image: AssetImage(roomImage),
                              height: double.infinity,
                              width: double.infinity,
                              fit: BoxFit.cover,
                            ),
                    ),


如果文件被选中,则所选文件否则显示默认设置图像。

yc0p9oo0

yc0p9oo01#

你必须使selectedCoverImage可观察,你可以使用GetX的Rx类。在你的例子中,你可以使用Rx<File>来创建一个可观察的selectedCoverImage。下面是你如何修改你的GetX控制器代码:

class YourController extends GetxController {

      Rx<File>? selectedCoverImage = Rx<File>(File(""));
    
      Future pickCoverImageFromGallery() async {
        final image = await ImagePicker()
            .pickImage(source: ImageSource.gallery, imageQuality: 70);
        if (image == null) return;
    
        selectedCoverImage.value = File(image.path);
      }
    }

字符串
现在你可以使用Obx方法:

Obx(
            () => controller.selectedCoverImage?.value != null
                ? Image.file(
                    controller.selectedCoverImage?.value??File(''),
                    height: double.infinity,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  )
                : Image(
                    image: AssetImage(roomImage),
                    height: double.infinity,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
          ),


希望这对你有帮助。

相关问题