我正在构建用户可以更改图像的编辑屏幕。我希望用户显示三个图像之一:-图像从服务器-临时图像,如果以前没有上传-新图像上传。
当我要从服务器显示图像时出现问题。使用未来的构建器可以显示图像,但不能上传新图像。如果我没有使用future builder,我会得到error
future不是ImageProvider类型的子类型
我的头像用于显示图像
CircleAvatar(
radius: MediaQuery.of(context).size.width / 6,
backgroundColor: Colors.grey,
backgroundImage: getImage(),
),
getImage ()
getImage() {
if (_image != null) {
if (uploadCounter == 0) {
uploadImage();
AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
backgroundColor: Colors.lightBlue[900],
content: Container(
child: Text('Uploading...'),
),
);
}
return FileImage(_image);
} else {
return _emptyImage;
}
}
And my upload image
uploadImage() async {
if (_image == null) {
showAlertDialog(
context: context,
title: "Error Uploading!",
content: "No Image was selected.");
return;
} else {
setState(() {
uploadStatus = true;
});
final preffs = await SharedPreferences.getInstance();
final token = preffs.getString('token');
final id = preffs.getString('id');
var uri = Uri.parse('http://10.0.2.2:8000/profiles/update/');
var request = http.MultipartRequest('PUT', uri)
..fields['id'] = id
..headers.addAll({"Authorization": token})
..files.add(await http.MultipartFile.fromPath('image_1', _image.path));
var response = await request.send();
if (response.statusCode == 200) {
print('Uploaded!');
print(response);
}
setState(
() {
uploadStatus = false;
uploadCounter = 1;
},
);
}
}
我试图通过未来构建器从服务器获取图像,或者在进入此屏幕之前保存图像,然后从文件中重新加载,但在flutter中保存文件不是最好的解决方案,我认为
目前唯一可行的解决方案如下:
FutureBuilder<Profile>(
future: profileService.getProfile(),
builder: (context, snapshot) {
if (snapshot.hasData) {
profile = snapshot.data;
return CircleAvatar(
radius: MediaQuery.of(context).size.width / 6,
backgroundColor: Colors.grey,
backgroundImage: Image.network(
"http://10.0.2.2:8000/" +
profile.image_1.toString())
.image,
);
} else {
return Container();
}
}),
CircleAvatar(
radius: 0.1,
backgroundColor: Colors.grey,
backgroundImage: getImage(),
),
如果我把第二个CircleAvatar在If -else返回,我会得到一些问题,如没有照片,只是灰色图像等,上传照片的问题。