Why does the image update only when I save file?
image_picker version
image_picker: ^0.8.4 3
My Code related to ImagePicker
// image_picker_controller.dart
// controller
import 'dart:io';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
class ImagePickerController extends GetxController {
File? pickedImageFile;
var seletedImagePath = ''.obs;
void _pickImage() async {
final picker = ImagePicker();
// final pickedImage = await picker.pickImage(source: ImageSource.gallery);
final pickedImage = await picker.pickImage(source: ImageSource.camera);
if (pickImage != null) {
pickedImageFile = File(pickedImage!.path);
}
update();
}
void Function() get pickImage => _pickImage;
}
view page
// user_image_picker.dart
// page screen
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_chatting_app/src/controllers/image_picker_controller.dart';
import 'package:get/get.dart';
class UserImagePicker extends GetView<ImagePickerController> {
UserImagePicker({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
CircleAvatar(
radius: 40,
backgroundColor: Colors.grey,
backgroundImage: controller.pickedImageFile != null
? FileImage(controller.pickedImageFile as File)
: null,
),
TextButton.icon(
onPressed: controller.pickImage,
icon: Icon(Icons.image),
label: Text('Add Image'),
),
],
);
}
}
You can have a look at what happens in this gif link
When I add image with ImagePicker, DEBUG CONSOLE shows below, and image isn't updated.
// DEBUG CONSOLE
D/MediaScannerConnection( 7062): Scanned /data/user/0/com.example.flutter_chatting_app/cache/bc149d80-91bb-487d-b2b7-3597357c4d182105624148556557573.jpg to null
but, after I save codes, the image appear. I think the state doens't update, but I have no idea why it happens.
I've googled about this problem, but I couldn't figure it out.
Please, somebody help me.
CodePudding user response:
I used the default Stateless
and GetBuilder
combination and it worked:
class ImagePickerController extends GetxController {
File? pickedImageFile;
void _pickImage() async {
final picker = ImagePicker();
final pickedImage = await picker.pickImage(source: ImageSource.camera);
pickedImageFile = File(pickedImage!.path);
update();
}
void Function() get pickImage => _pickImage;
}
and the view:
class UserImagePicker extends StatelessWidget {
const UserImagePicker({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetBuilder<ImagePickerController>(builder: (logic) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CircleAvatar(
radius: 40,
backgroundColor: Colors.grey,
backgroundImage: logic.pickedImageFile != null
? FileImage(logic.pickedImageFile as File)
: null,
),
TextButton.icon(
onPressed: logic.pickImage,
icon: const Icon(Icons.image),
label: const Text('Add Image'),
),
],
);
});
}
}