如何将图像数据从FirebaseStorage保存到数据库并使用Flutter中的CircleAvatar检索它们

时间:2020-08-17 17:22:24

标签: flutter dart firebase-storage

您好,我想将我的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,
                            ),
                          ),
                        ),
                      ),

H ere是异常错误

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)

1 个答案:

答案 0 :(得分:1)

将您的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来上传图片并返回其网址以存储在profilePicture键中。

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中轻松显示数据库中的图像,因为您具有其网址

            CircleAvatar(
                      backgroundColor: Colors.white70,
                      child: ClipOval(
                        child: new SizedBox(
                          // width: 180.0,
                          // height: 180.0,
                          child: 
                    Image.network(listContact[index].profilepicture,
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    ),

这是结果!

Here is the result

相关问题