ImagePicker,如何再次设置图像? [英] ImagePicker, how to set image again?
问题描述
最小代码:
File _file;
Future<void> _pickImage() async {
final image = await ImagePicker.pickImage(source: ImageSource.camera);
if (image != null) {
final file = File("${(await getApplicationDocumentsDirectory()).path}/image.png");
await file.writeAsBytes(await image.readAsBytes());
setState(() => _file = file); // `_file = image` works though
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(child: Icon(Icons.camera_alt), onPressed: _pickImage),
body: _file == null ? Container() : Image.file(_file),
);
}
如您所见,一旦我选择了图像,可以,但是在第二次选择时,它不起作用,我也没有遇到任何错误。有人可以帮忙吗?
As you can see, once I pick the image, it works, but on picking it second time, it doesn't work and I also don't run into any error. Can anyone please help?
推荐答案
您需要3件事:
首先,您必须使用 ImageProvider
及其 evict()
方法:
first you have to use ImageProvider
and its evict()
method:
var image = FileImage(File('someImage.jpg'));
然后您需要使用上面的 Image
小部件 ImageProvider
,并且还分配唯一的 key
以便每次 build( )
方法被称为:
then you need Image
widget that uses above ImageProvider
and also assigns a unique key
in order to be "different" each time build()
method is called:
child: Image(
image: image,
key: UniqueKey(),
),
,最后覆盖 someImage.jpg
您必须调用 evict()
方法:
and finally after you overwrite someImage.jpg
you have to call evict()
method:
// part of your _pickImage() method
// here someImage.jpg contains updated content
image.evict();
setState(() {});
更新:实际上,您不需要 var image = FileImage(File('someImage.jpg'));
-您可以在 Image
小部件内直接使用它作为 image :FileImage(File('someImage.jpg'))
,然后调用 FileImage(File('someImage.jpg'))。evict()
您的图片已被覆盖
UPDATE: actually you dont need var image = FileImage(File('someImage.jpg'));
- you can use it directly inside Image
widget as image: FileImage(File('someImage.jpg'))
and call FileImage(File('someImage.jpg')).evict()
after your image is ovewritten
这篇关于ImagePicker,如何再次设置图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!