flutter state change on - flutter

class _EventAdminEditState extends State<EventAdminEdit> {
#override
Widget build(BuildContext context) {
String imageURL = widget.ccaDocument['Image'];
final GlobalKey<FormState> _key = GlobalKey();
final TextEditingController imageURLController = new TextEditingController();
imageURLController.text = imageURL;
void _publishEvent() async {
print(imageURL);
widget.ccaDocument.reference.updateData({
'Name' : name,
'Details': details,
'Location': location,
'RegisterInstructions': registrationInstructions,
'EventTime': eventTime,
'Image' : imageURL
}
Future uploadImage(BuildContext context) async {
final picker = ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
StorageReference firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('event_profile/${Path.basename(_image.path)}}');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
setState(() {
imageURL = dowurl.toString();
});
Hi, Can I ask why the imageURL doesn't change even though I called setState() implicitly.
I tried printing it out to confirm to see if the image URL inside upload image is changed.
ImageURL inside upload image is changed but however the global imageURL in publishEvent is unchanged.
What I am trying to do is to change the image that is being uploaded.
Can someone with me out?
Thank you.

String imageURL = widget.ccaDocument['Image'];
this code is in your build, so everytime you call setState(() {}); this is setting your imageUrl.
You need to use initState and set your imageUrl there
String imageURL;
void initState() {
super.initState();
imageURL = widget.ccaDocument['Image'];
}

Related

How can I show first time that getting image from firebase storage in my app?

I define pick image and photoUrl variables:
File? image;
String? photoUrl;
This is my pick image method:
Future pickImage(ImageSource source) async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
this.image = imageTemporary;
});
} on PlatformException catch (e) {
print('Failed to pick image : $e');
}
}
This is my upload image function ı upload image with current user ids:
Future uploadFile() async {
final path = '${_auth.currentUser!.uid}.jpg';
final file = File(image!.path);
final ref = FirebaseStorage.instance
.ref()
.child('images/${_auth.currentUser!.uid}.jpg');
task = await ref.putFile(file);
//final url = await ref.getDownloadURL();
//print('Download URLLLLLLLLLLLLLLLLLLLLL : $url');
/*
I saved download image url to setstate method
setState(() {
photoUrl = url.toString();
});
*/
}
This is my download image and init state method, when I upload image to firebase storage first time, ı am getting no object exist at desired reference error, but after ı upload image then I try
to download image and I want to show in image.network it works, How can I fix this error when I try to upload and download first time without error ?
Future downloadImage() async {
final ref = FirebaseStorage.instance
.ref()
.child('images/${_auth.currentUser!.uid}.jpg');
final url = await ref.getDownloadURL();
print('Download URLLLLLLLLLLLLLLLLLLLLL : $url');
setState(() {
photoUrl = url.toString();
});
}
#override
initState() {
// TODO: implement initState
super.initState();
downloadImage();
}
This is my error:
and
this is my storage its empty :
The problem seems to be that you are trying to get the url before uploading the image, Here is what you can do :
uploadImage() async {
final _firebaseStorage = FirebaseStorage.instance;
final _imagePicker = ImagePicker();
PickedFile image;
//Check Permissions
await Permission.photos.request();
var permissionStatus = await Permission.photos.status;
if (permissionStatus.isGranted){
//Select Image
image = await _imagePicker.getImage(source: ImageSource.gallery);
var file = File(image.path);
if (image != null){
//Upload to Firebase
var snapshot = await _firebaseStorage.ref()
.child('images/imageName')
.putFile(file).onComplete;
var downloadUrl = await snapshot.ref.getDownloadURL();
setState(() {
imageUrl = downloadUrl;
// in here you can add your code to store the url in firebase database for example:
FirebaseDatabase.instance
.ref('users/$userId/imageUrl')
.set(imageUrl)
.then((_) {
// Data saved successfully!
})
.catchError((error) {
// The write failed...
});
});
} else {
print('No Image Path Received');
}
} else {
print('Permission not granted. Try Again with permission access');
}
source How to upload to Firebase Storage with Flutter
I hope this will be helpfull

Save ImagePicker Image in Shared Preferences - Flutter

I'm trying to save image picked from ImagePicker and store it in shared preferences and then retrieve it from there but no luck so far
To make my question more specific, how to save an image as a string in shared preference and then later retrieve it
Here is my code
File? profileImage;
void saveData(String key, String value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(key, value);
}
void getData(String key) async {
final prefs = await SharedPreferences.getInstance();
final image = await prefs.getString(key);
setState(() {
profileImage = image; //this would result into error because profileImage expect file type value
});
}
Future pickProfile() async {
final profileImagePicker = await ImagePicker().pickImage(source: ImageSource.gallery);
final File profile = File(profileImagePicker!.path);
final directoryPath = await getApplicationDocumentsDirectory();
final path = directoryPath.path;
final imageFile = await File(profileImagePicker.path).copy('$path/image1.png'); // What am I supposed to do after this step
saveData('profile', path); what value needs to be stored here, it expects a string
setState(() {
profileImage = profile;
});
}
To convert image into String you can use below code
final bytes = imageFile.readAsBytesSync();
String imageString = base64Encode(bytes);
To convert String to Image
Uint8List bytes = BASE64.decode(base64ImageString);
You can use the Image widget to diplay the Image
Image.memory(bytes);

Upload Image Flutter Storage

i am use 'image_picker_web/image_picker_web.dart' in my app. Now when I choosed image, this image displayed, it's work. But when i try to save image in storage nothing happens.
Uint8List _image1;
Future getImg() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
// debugPrint(tempImg.toString());
_image1 = tempImg;
});
}}
save in storage:
void uploadImg() async {
final StorageReference productImg =
FirebaseStorage.instance.ref().child('ProductImg');
var timekey = DateTime.now();
final StorageUploadTask uploadTask =
productImg.child(timekey.toString() + 'jpg').putData(_image1);
var imageUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
url = imageUrl.toString();
print('Image Url' + url);}
button:
RaisedButton(
onPressed: () {
uploadImg();
}
what am I doing wrong?
Give this a try:
final file = File.fromRawPath(uint8list);
final ref = FirebaseStorage.instance.ref().child("users/some_id/ProductImg.jpg");
final task = ref.putFile(file, StorageMetadata(contentType: "image/png"));
final snapshot = await task.onComplete;
if (snapshot.error != null) throw snapshot.error;
final downloadURL = await snapshot.ref.getDownloadURL();

Convert Uint8List to File

I'm using Image Picker web which works well. I can display image in Image.memory(), but this image in format Uintlist8. For save in storage need format File, my issue is how to save an image in Firebase Storage.
Web image picker:
class _SecondPageState extends State<SecondPage> {
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
});
}
}
Please Try ....
final _formkey = GlobalKey<FormState>();
Uint8List _image;
getImage() async {
Uint8List tempImg = await ImagePickerWeb.getImage(asUint8List: true);
if (tempImg != null) {
setState(() {
_image = tempImg;
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.jpg').create();
file.writeAsBytesSync(_image);
});
}
}

Converting of Image File created using image_picker package of flutter to AssetImage/Image.asset?

I am new to flutter, i am building an app where i need to convert the file(image) generated after using image_picker package to asset image to use in the app.
example code as follows, which creates file(Image)
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
}
Thanks in advance
You can create an image variable which you can rever to and update when you selected the image.
See the following code:
final Function onSelectImage;
ImageInput(this.onSelectImage);
File _storedImage;
Image _tempImage;
Future<void> _takePicture() async {
final imageFile = await ImagePicker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
);
if (imageFile == null) {
return;
}
setState(() {
_storedImage = imageFile;
});
final appDir = await syspaths.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appDir.path}/$fileName');
widget.onSelectImage(savedImage);
setState(() {
_tempImage = imageFile;
});
}
#override
Widget build(BuildContext context) {
return _tempImage == null ? Container(child:null) : Image(image: _tempImage);
}