0

这是我学习 getx 处理图像的又一次冒险。我从另一个来源获取了这段代码,但它并没有解决我的问题。我适合我自己的例子。如何使用选定的图像更新我的 BoxDecoration 小部件?

以下是我的小部件

            GestureDetector(
            onTap: () => {_onPictureSelection()},
            child:Container(
              height: screenHeight / 3.2,
              width: screenWidth / 1.8,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: imageController.image == null
                      ? AssetImage(pathAsset)
                      : FileImage(imageController.image),
                  fit: BoxFit.cover,
                ),
                border: Border.all(
                  width: 3.0,
                  color: Colors.grey,
                ),
                borderRadius: BorderRadius.all(
                    Radius.circular(5.0) //         <--- border radius here
                    ),
              ),
            )),

           _onPictureSelection() async {
              imageController.getImage();
            }

这是我的图像控制器

class ImageController extends GetxController {
static ImageController get to => Get.find<ImageController>();

File image;
String imagePath;
final _picker = ImagePicker();

Future<void> getImage() async {
final pickedFile = await _picker.getImage(source: ImageSource.camera);

if (pickedFile != null) {
  image = File(pickedFile.path);
  imagePath = pickedFile.path;
  print(imagePath);
  update();
 } else {
  print('No image selected.');
 }
}
}

如何使用通过相机拍摄的图像更新我的 BoxDecoration 小部件,以及在哪里用我的小部件包装 obx?

4

2 回答 2

1

请在ImageController类的代码中替换以下条件。

if (pickedFile != null) {
    image = File(pickedFile.path);
    imagePath = pickedFile.path;
    print(imagePath);
    update();
} else {
   print('No image selected.');
}
于 2021-03-10T06:45:55.907 回答
0

经过多次尝试和错误,我终于明白了。

我用 GetBuilder 更新了我的 GestureDetector 小部件

GestureDetector(
            onTap: () => {_onPictureSelection()},
            child: GetBuilder<ImageController>(
                // specify type as Controller
                init: ImageController(), // intialize with the Controller
                builder: (value) => Container(
                      height: screenHeight / 3.2,
                      width: screenWidth / 1.8,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: imageController.image == null
                              ? AssetImage(pathAsset)
                              : FileImage(imageController.image),
                          fit: BoxFit.cover,
                        ),
                        border: Border.all(
                          width: 3.0,
                          color: Colors.grey,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(
                                5.0) //         <--- border radius here
                            ),
                      ),
                    ))),

最后它开始工作了。

于 2021-03-16T00:15:34.087 回答