如何在 Getx 控制器中使用可观察的 File 变量

问题描述 投票:0回答:1

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

错误

      [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,
                            ),
                    ),

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

flutter dart state-management gets flutter-design
1个回答
0
投票

你必须使 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);
      }
    }

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.