Flutter with Getx ImagePicker不能正常工作



为什么只有保存文件时图像才更新?

image_picker版本

image_picker: ^0.8.4+3

我的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;
}

视图页面

// 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'),
),
],
);
}
}

你可以看看发生了什么在这个gif链接

当我用ImagePicker添加图像时,DEBUG控制台显示如下,并且图像没有更新。

// DEBUG CONSOLE
D/MediaScannerConnection( 7062): Scanned /data/user/0/com.example.flutter_chatting_app/cache/bc149d80-91bb-487d-b2b7-3597357c4d182105624148556557573.jpg to null

但是,在我保存代码之后,图像出现了。我认为国家没有更新,但我不知道为什么会这样。

我在谷歌上搜索过这个问题,但我还是不明白。

谁来帮帮我。

我使用默认的StatelessGetBuilder组合,它工作:

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;
}

和视图:

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'),
),
],
);
});
}
}

相关内容

  • 没有找到相关文章

最新更新