Как отобразить изображение после использования камеры с использованием Getx Flutter?

#flutter #flutter-getx

#флаттер #flutter-getx

Вопрос:

Как отобразить изображение после использования камеры с использованием Getx Flutter? он показывает AssetImage (‘assets/images/kad.jpg ‘) но после съемки он не показывает изображение с камеры.. пожалуйста, помогите мне

 imageController.dart
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);
      File imagePath = File(pickedFile.path);
      print(imagePath);
    } else {
      print('No image selected.');
    }
  }
}
  

здесь, на UI.dart

 class UploadPicture extends StatelessWidget {
  final imageController = ImageController.to;
..........
image: DecorationImage(
   image: imageController.image == null
          ? AssetImage('assets/images/kad.jpg')
          : Image.file(File(imageController.image.path))),```
   
it show AssetImage('assets/images/kad.jpg') but after take picture it not show the picture from camera.. please help me
  

Ответ №1:

Я думаю, вам не хватает метода update () внутри функции getImage ()

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

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

Ответ №2:

проблема решена. не удается поместить изображение.файл в разделе DecorationImage. Tq все

 DecorationImage(image: Image.file(File(imageController.image.path)) //wrong  

DecorationImage(image: AssetImage('assets/images/kad.jpg')) //right

  

Ответ №3:

Контроллер

 class ImageController extends GetxController {
  final ImagePicker imagePicker = ImagePicker();
  final pickedImage = Rx<File?>(null);
  final imagefiles = RxList<File>([]);
  Future<void> pickMultiImage() async {
    try {
      var pickedfile = await imagePicker.pickImage(source: ImageSource.camera);

      //you can use ImageCourse.camera for Camera capture
      if (pickedfile != null) {
        pickedImage.value = File(pickedfile.path);
        imagefiles.add(pickedImage.value!);
      }
    } catch (e) {
      print('error while picking file.');
    }
  }
}
  

Страница

Изображение отображается в Gridview

 class TestPage extends StatelessWidget {
  final imageController = Get.put(ImageController());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KAppbar(),
      body: Obx(
        () => SingleChildScrollView(
            child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Row(
                children: [
                  SizedBox(
                    width: 5,
                  ),
                  IconButton(
                    onPressed: () {
                      imageController.pickMultiImage();
                    },
                    icon: Icon(Icons.add_a_photo),
                    iconSize: 40,
                  ),
                  Text(
                    'Attachments',
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 10,
            ),
            imageController.imagefiles.isEmpty
                ? GridView.builder(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 15,
                    ),
                    itemCount: 1,
                    primary: false,
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        // height: 130,
                        width: double.infinity,
                        color: Colors.amber,
                        child: Center(
                          child: IconButton(
                            onPressed: () => imageController.pickMultiImage(),
                            icon: Icon(
                              Icons.add,
                              color: Colors.grey,
                              size: 15,
                            ),
                          ),
                        ),

                        //background color of inner container
                      );
                    },
                  )
                : GridView.builder(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                    ),
                    itemCount: imageController.imagefiles.length,
                    primary: false,
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      final item = imageController.imagefiles[index];
                      return Stack(
                        children: [
                          Container(
                            width: double.infinity,
                            margin: EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(5),
                              child: Image.file(
                                File(item.path),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          Positioned(
                            top: 0,
                            right: 0,
                            left: 0,
                            bottom: 0,
                            child: InkWell(
                              onTap: () {
                                //if you want to remove image
                                imageController.imagefiles.removeAt(index);
                              },
                              child: Container(
                                margin: EdgeInsets.all(60),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(50),
                                  color: Colors.white.withOpacity(0.5),
                                ),
                                child: Icon(
                                  Icons.delete,
                                  color: Colors.redAccent,
                                  size: 30,
                                ),
                              ),
                            ),
                          ),
                        ],
                      );
                    },
                  ),
          ],
        )),
      ),
    );
  }
}