Следующая ошибка _CastError была вызвана сборкой RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#0cfc0]

Здравствуйте, я пытаюсь добавить изображение в приложение с помощью средства выбора изображений, но когда я закрываю экран и снова открываю его, это сообщение отображается для меня.

      ════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#0cfc0](state: RawGestureDetectorState#aaba3(gestures: <none>, behavior: opaque)):
Null check operator used on a null value

The relevant error-causing widget was
SingleChildScrollView
lib\screens\create_post.dart:22
When the exception was thrown, this was the stack

и что мой код CreatePost Screen

      Scaffold(
        body: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                height: MediaQuery.of(context).size.height * 0.25,
                decoration: BoxDecoration(
                  color: primary,
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(100),
                  ),
                ),
                child: CustomText(
                  text: 'Sell Your Car',
                  alignment: Alignment.center,
                  fontSize: 40,
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.05,
              ),
              CustomTextFormFild(onSave: () {}, hint: 'car name'),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.05,
              ),
              CustomTextFormFild(onSave: () {}, hint: 'car description'),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.05,
              ),
              GetBuilder<ImageViewModel>(
                builder: (controller) => Column(
                  children: [
                    Container(
                      child: CustomButton(
                        onPressed: () {
                          controller.getImage(ImageSource.gallery);
                        },
                        text: 'Upload Image',
                        alignment: Alignment.center,
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    controller.selectedImagePath.value == ''
                        ? Text(
                            'Select immage from camera/gallery',
                            style: TextStyle(fontSize: 20),
                          )
                        : Image.file(File(controller.selectedImagePath.value)),
                  ],
                ),
              )
            ],
          ),
        ),)

а также контроллер средства выбора изображений

      class ImageViewModel extends GetxController {
  //TODO: Implement HomeController

  var selectedImagePath = ''.obs;

  void getImage(ImageSource imageSource) async {
    final pickedFile = await ImagePicker().pickImage(source: imageSource);

    if (pickedFile != null) {
      selectedImagePath.value = pickedFile.path;
    } else {
      Get.snackbar("Error", "No Image selected",
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red,
          colorText: Colors.white);
    }
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {}
}

что-то пошло не так изображение должно быть удалено после того, как я закрою экран, но это не работает

1 ответ

Вы должны инициализировать контроллер следующим образом:

      GetBuilder<ImageViewModel>(
                init: ImageViewModel(),
                builder: (controller) => ...
Другие вопросы по тегам