我试图永久保存从相机或画廊上传的图像,我使用image_picker
包,每次我为pfp选择一张图片并单击不同的选项卡,它就消失了,它只是暂时保存它。下面是我的代码:
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
// camera
Future getCameraImage() async{
// getting the image
final image = await ImagePicker().pickImage(source: ImageSource.camera);
if(image == null) return;
// final imageTemporary = File(image.path);
final imagePerm = await saveImagePermanently(image.path);
setState(() {
this.image = imagePerm;
});
}
// image picker/ gallery
File? image;
Future getImage() async{
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if(image == null) return;
final imageTemporary = File(image.path);
setState(() {
this.image = imageTemporary;
});
}
我尝试了几种不同的方法,但都遇到了同样的错误。
按以下步骤操作:
// Step 1: Retrieve image from picker
final File image = await ImagePicker.pickImage(source: imageSource);
// Step 2: Check for valid file
if (image == null) return;
// Step 3: Get directory where we can duplicate selected file.
final String path = await getApplicationDocumentsDirectory().path;
// Step 4: Copy the file to a application document directory.
final var fileName = basename(file.path);
final File localImage = await image.copy('$path/$fileName');
StatefulWidget
有一个生命周期,当你在底部导航栏中导航屏幕时,你正在杀死那些没有显示在屏幕上的小部件的状态。
所以切换到其他屏幕,当你选择一个图像,File? image;
应该有图像文件被杀死,所以当你回到那个屏幕,这个小部件被重新构建,这将导致它只是空的,它失去了之前的值。
这个问题的解决方案是在全局作用域中设置变量,它永远不会被重新初始化为null
,如:
File? image;
class YourStateFulWidget extends StateFulWidget {
/* all your widget and State object code*/