flutter - 如何将图像数据从 FirebaseStorage 保存到数据库并在 Flutter 中使用 CircleAvatar 检索它
问题描述
嗨,我试图将我的图像数据从 firebase 存储插入到我的数据库中,但是我在使用 Floor 作为我的数据库时所没有的所有想法,任何建议或想法都将不胜感激。
这是我从firebase获取图像的代码 将图像存储到数据库
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
imgString = Utility.base64String(image.readAsBytesSync()); //here where i get the image
setState(() {
_image = image;
print('Image Path $_image');
});
}
Future uploadPic(BuildContext context) async {
String fileName = Path.basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref()
.child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// setState(() {
print("Profile Picture uploaded");
// Scaffold.of(context).showSnackBar(SnackBar(content: Text('Profile Picture Uploaded')));
Fluttertoast.showToast(
msg: 'New Data was Uploaded',
toastLength: Toast.LENGTH_SHORT,
timeInSecForIosWeb: 1,
gravity: ToastGravity.BOTTOM);
// });
}
这是我将图像数据保存到数据库的代码
insertData() async {
if(widget.firstnameController.text.isNotEmpty && widget.lastnameController.text.isNotEmpty &&
widget.contactnumberController.text.isNotEmpty && widget.birthdayController.text.isNotEmpty) {
var addContacts = ContactObject(
firstname: widget.firstnameController.value.text,
lastname: widget.lastnameController.value.text,
birthday: widget.birthdayController.value.text,
contactnumber: int.parse(widget.contactnumberController.value.text),
profilepicture: Utility.imageFromBase64String(imgString).toString()); //Here is the image data
await _contactsDao.insertContact(addContacts);
} else {
print('ERROR');
}
Future.delayed(Duration(seconds: 2)).then((value) {
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (BuildContext context) => Contactscreen()));
});
}
这是我的代码,我将其转换为 base64 数据
class Utility {
static Image imageFromBase64String(String base64String) {
return Image.memory(
base64Decode(base64String),
fit: BoxFit.fill,
);
}
static Uint8List dataFromBase64String(String base64String) {
return base64Decode(base64String);
}
static String base64String(Uint8List data) {
return base64Encode(data);
}
}
在这里我调用/显示图像数据到 circleAvatar
CircleAvatar(
backgroundColor: Colors.white70,
child: ClipOval(
child: new SizedBox(
// width: 180.0,
// height: 180.0,
child: Image.file(File('${listContact[index].profilepicture}'),
fit: BoxFit.fill,
),
),
),
),
这是异常错误
Cannot open file, path = 'Image(image: MemoryImage(Uint8List#1a942, scale: 1.0), frameBuilder: null, loadingBuilder: null, fit: fill, alignment: center, this.excludeFromSemantics: false, filterQuality: low)' (OS Error: No such file or directory, errno = 2)
解决方案
将您的uploadPic
功能修改为:
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
static Future<String> uploadPic(String path) async {
String fileName = DateTime.now().toIso8601String();
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(File(path));
var url = await (await uploadTask.onComplete).ref.getDownloadURL();
return url;
}
上面的函数将获取图像的路径,然后返回它的 url,您可以将其插入数据库。您现在可以轻松地显示数据库中的图像,因为您已经存储了它的 url。
在插入数据函数中,您需要再次调用uploadPic 来上传图像并返回其url 以存储在profilePicture
key 中。
insertData() async {
if (widget.firstnameController.text.isNotEmpty &&
widget.lastnameController.text.isNotEmpty &&
widget.contactnumberController.text.isNotEmpty &&
widget.birthdayController.text.isNotEmpty) {
var addContacts = ContactObject(
firstname: widget.firstnameController.value.text,
lastname: widget.lastnameController.value.text,
birthday: widget.birthdayController.value.text,
contactnumber: int.parse(widget.contactnumberController.value.text),
// pass path of image in this function. for ex (if image is stored in map use image.values.first (it will return path)
profilepicture: await uploadPic(_image.path)
); //Here is the image data
await _contactsDao.insertContact(addContacts);
} else {
print('ERROR');
}
Future.delayed(Duration(seconds: 2)).then((value) {
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (BuildContext context) => Contactscreen()));
});
}
最后,您可以在 Image.network 中轻松显示数据库中的图像,因为您有它的 url
CircleAvatar(
backgroundColor: Colors.white70,
child: ClipOval(
child: new SizedBox(
// width: 180.0,
// height: 180.0,
child:
Image.network(listContact[index].profilepicture,
fit: BoxFit.fill,
),
),
),
),
这是结果!
推荐阅读
- swift - 如何使用 yolo.h5 设置 coremltools 转换模型输出形状
- java - 如何从不同的主机连接到服务器套接字?
- ios - 检查何时在 iOS 中显示系统警报
- java - 预订系统的日期验证
- javascript - WordPress:将自定义样式添加到 Gutenberg 组块
- go - String formatting has precision in Go?
- php - 致命错误:未捕获的错误:在 C:\xampp\htdocs\Powerpoint Learner Pro\php\Course_Action.php:27 中调用 bool 上的成员函数 bind_param()
- machine-learning - 当前最好的 GAN 模型训练 cifar10 是什么?
- java - 我无法在表格视图中设置按钮宽度
- r - R中条件逻辑回归期间错误的解决方案是什么?