// Unhandled Exception: Null check operator used on a null value// - flutter

When i click on camera icon in stack widget and also it is unable to update image it show this error.It also not upload image to database nor it chaange the url** [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value E/flutter (28471): #0 _profileState.geturl (package:ecommerce/Auth/profile.dart:25:59) E/flutter (28471): **
I want to update image but facing error please solve it..
Code For Imagepicker
Future image(BuildContext context) async{
showModalBottomSheet(
elevation: 5,
enableDrag: true,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
child: Column(
children: [
///Gallery
ListTile(
leading: Icon(Icons.browse_gallery),
title: Text("Pick image from gallery"),
onTap: () async{
final gallery=await ImagePicker().pickImage(source: ImageSource.gallery);
if (gallery!=null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Image Picked successfull",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Please pick image for further proccess",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
}
Code For updating Url
Future geturl(context)async{
final id=DateTime.now().toString();
final reference=FirebaseFirestore.instance.collection("user3");
await image(context);
final storage.Reference ref =
storage.FirebaseStorage.instance.ref('/images'+id);
final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
await Future.value(uploadTask);
final downurl=await ref.getDownloadURL();
print(FirebaseAuth.instance.currentUser!.uid);
reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
{
"imageurl":downurl.toString(),
}
).then((value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
}).catchError((e){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
});
}
For displaying image in flutter app
Stack(
alignment: Alignment.bottomRight,
children: [
CircleAvatar(
radius: 70,
backgroundImage:_image!=null?FileImage(_image!.absolute) : NetworkImage(snapshot.data!.docs[index]["imageurl"]) as ImageProvider,
),
InkWell(
onTap: (){
geturl(context);
},
child: Icon(Icons.add_a_photo,size: 30,)),
],
),
Please solve I am facing this error for Last couple of days

You need to declare the image variable null by adding "?".
Example: DataType image?
Then display like this
image!=null ? CircleAvatar(
radius: 70,
backgroundImage: FileImage(_image!.absolute) ,
): CircleAvatar(
radius: 70,
backgroundImage: NetworkImage(snapshot.data!.docs[index]["imageurl"])

I think that this line is causing the problem:
final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
Because _image is probably null. Where do you assign a value to the variable _image?
EDIT:
how I would fix this:
you have one method pickImage that shows the bottom modal sheet and allows the user to pick an image. if the user picks an image, you call a method that saves the picked image to firebase, in this case the method is called: saveImage
void pickImage(BuildContext context) {
showModalBottomSheet(
elevation: 5,
enableDrag: true,
isDismissible: false,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
context: context,
builder: (BuildContext context) {
return Container(
height: 200,
child: Column(
children: [
ListTile(
leading: Icon(Icons.browse_gallery),
title: Text("Pick image from gallery"),
onTap: () async {
XFile? pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
if (pickedImage != null) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
"Image Picked successfull",
style: TextStyle(color: Colors.redAccent),
),
duration: Duration(seconds: 5),
));
var image = Image.memory(await pickedImage.readAsBytes());
// save image to firebase
saveImage(context, image);
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text(
"Please pick image for further proccess",
style: TextStyle(color: Colors.redAccent),
),
duration: Duration(seconds: 5),
));
}
},
),
],
),
);
},
);
}
method that saves the image to firebase:
Future saveImage(context, _image) async {
final id = DateTime.now().toString();
final reference=FirebaseFirestore.instance.collection("user3");
final storage.Reference ref =
storage.FirebaseStorage.instance.ref('/images'+id);
final storage.UploadTask uploadTask = ref.putFile(_image!.absolute);
await Future.value(uploadTask);
final downurl=await ref.getDownloadURL();
print(FirebaseAuth.instance.currentUser!.uid);
reference.doc(FirebaseAuth.instance.currentUser!.uid).update(
{
"imageurl":downurl.toString(),
}
).then((value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Updated successfully",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
}).catchError((e){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
});
}

Related

Delete profile in firebase flutter

I need to delete the users profile from firebase, thing is I have 3 collections petfiles, petsdetails and users which need to be deleted. As in when a user signs up, they can create a pet and create records for their pet. But when having to delete the user, it should delete all the pets and records the pet has (it could be up to any amount)
I havent tried anything as I dont really know how to solve this but this is my code
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vet_bookr/oScreens/petFiles.dart';
import '../constant.dart';
class UserDetails extends StatefulWidget {
UserDetails({Key? key, required this.details}) : super(key: key);
Map<String, dynamic> details;
#override
State<UserDetails> createState() => _UserDetailsState();
}
class _UserDetailsState extends State<UserDetails> {
List<String> labels = ["Email", "Phone Number"];
bool editableText = false;
String imageUrl = "";
List<String> petIds = [];
#override
void initState() {
// TODO: implement initState
nameController.text = widget.details["name"];
ageController.text = widget.details["age"];
super.initState();
}
Future<void> uploadImages({required String path}) async {
try {
final imageRef = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await imageRef.putFile(File(path));
imageUrl = await imageRef.getDownloadURL();
setState(() {});
//print(imageRef.getDownloadURL());
} on FirebaseException catch (e) {
print("Function does work");
SnackBar snackBar = SnackBar(content: Text(e.message!));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
}
bool isLoading = false;
final nameController = TextEditingController();
final ageController = TextEditingController();
XFile? profilePic;
ImagePicker imagePicker = ImagePicker();
final storageRef = FirebaseStorage.instance.ref();
TextEditingController controllerChanger(index) {
if (index == 0) {
return nameController;
}
if (index == 1) {
return ageController;
}
return TextEditingController();
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
appBar: AppBar(
systemOverlayStyle: SystemUiOverlayStyle.dark,
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.pop(context);
},
),
actions: [
Padding(
padding: EdgeInsets.only(right: 5.sp),
child: PopupMenuButton(
icon: Icon(
Icons.more_vert,
color: Colors.black,
),
itemBuilder: (context) {
return [
PopupMenuItem<int>(
value: 0,
child: Text("Edit Profile"),
),
PopupMenuItem<int>(
value: 1,
child: Text("Delete Profile"),
),
];
},
onSelected: (value) async {
if (value == 0) {
setState(() {
editableText = true;
});
print(editableText);
} else if (value == 1) {
setState(() {
isLoading = true;
});
final ref = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await ref.delete();
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.delete();
DocumentSnapshot<Map<dynamic, dynamic>> snap =
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.get();
await FirebaseFirestore.instance
.collection("petDetails")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!),
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayUnion(snap.data()!["pets"]!),
});
setState(() {
isLoading = false;
});
Navigator.pop(context);
}
},
))
],
),
extendBodyBehindAppBar: true,
backgroundColor: kBackgroundColor,
body: isLoading
? Container(
width: 1.sw,
height: 0.4.sh,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 15.sp,
width: 15.sp,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Color(0xffFF8B6A),
),
),
],
),
)
: SafeArea(
child: Container(
//alignment: Alignment.center,
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(15.sp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// sBox(h: 10),
Text(
'Pet Information',
style: TextStyle(
color: Color(0xffF08519), fontSize: 0.05.sw),
),
// myPetTile()
SizedBox(
height: 0.05.sh,
),
Stack(
children: [
CircleAvatar(
radius: 0.095.sh,
backgroundColor: Color(0xffFF8B6A),
backgroundImage: profilePic == null
? NetworkImage(
widget.details["profilePicture"],
)
: null,
child: profilePic == null
? Container(
width: 0,
height: 0,
)
: ClipRRect(
borderRadius:
BorderRadius.circular(100),
child: Image.file(
File(
"${profilePic?.path}",
),
),
),
),
editableText
? Positioned(
right: 0.025.sw,
bottom: 0.005.sh,
child: GestureDetector(
onTap: () async {
profilePic = await ImagePicker()
.pickImage(
source: ImageSource.gallery);
setState(() {});
},
child: CircleAvatar(
backgroundColor: Color(0xffFF8B6A),
radius: 0.02.sh,
child: Icon(
Icons.camera_alt_outlined,
size: 0.05.sw,
color: Colors.white,
),
),
),
)
: Container(
width: 0,
height: 0,
)
],
),
SizedBox(
height: 0.02.sh,
),
...List.generate(
2,
(index) => Padding(
padding: EdgeInsets.only(
top: 0.02.sh, left: 0.05.sw, right: 0.05.sw),
child: TextField(
enabled: editableText,
controller: controllerChanger(index),
style: TextStyle(fontSize: 0.017.sh),
cursorColor: Colors.black,
decoration: InputDecoration(
label: Text(labels[index],
style: TextStyle(fontSize: 0.02.sh)),
labelStyle: TextStyle(color: Colors.black54),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.sp),
borderSide:
BorderSide(color: Color(0xffFF8B6A))),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.sp),
),
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.circular(10.sp),
borderSide:
BorderSide(color: Color(0xffFF8B6A))),
contentPadding:
EdgeInsets.symmetric(horizontal: 10.sp),
hintStyle: TextStyle(color: Colors.grey),
),
),
),
),
buttonWidget()
],
),
),
),
),
),
),
);
}
bool isLoadingEdit = false;
Widget buttonWidget() {
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 0.4.sw,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
backgroundColor: Color(0xffFF8B6A),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.sp),
),
),
onPressed: () async {
if (editableText) {
setState(() {
isLoadingEdit = true;
});
if (profilePic != null) {
final ref = storageRef.child(
"Users/${FirebaseAuth.instance.currentUser?.uid}/${widget.details["id"]}");
await ref.delete();
await uploadImages(path: profilePic!.path);
}
await FirebaseFirestore.instance
.collection("petsDetails")
.doc(widget.details["id"])
.update({
'name': nameController.text,
'age': ageController.text,
'breed': breedController.text,
'weight': weightController.text,
'profilePicture': profilePic != null
? imageUrl
: widget.details["profilePicture"],
'lastVaccinationDate':
widget.details["lastVaccinationDate"]
});
DocumentSnapshot<Map<String, dynamic>> snap =
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.get();
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!)
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayRemove(snap.data()!["pets"]!),
});
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser?.uid)
.update({
'pets': FieldValue.arrayUnion(snap.data()!["pets"]!),
});
Navigator.pop(context);
setState(() {
isLoadingEdit = false;
editableText = false;
});
const snackBar = SnackBar(
content: Text("Your pet's details have been changed"),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PetFiles(
petId: widget.details["id"],
),
),
);
}
},
child: isLoadingEdit
? Container(
height: 15.sp,
width: 15.sp,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2.sp,
),
)
: Text(
editableText ? "Save Changes" : "Pet Health Records",
style:
TextStyle(color: Colors.white, fontSize: 0.03.sw),
),
),
),
],
),
SizedBox(
height: 0.01.sh,
),
],
);
}
}
You can check out their official docs for deleting collections here.
Or you can upgrade your project to blaze plan and use this extension which takes care of it for you.
Alternatively you can use NodeJS and FirebaseFunctions to do this task for you. Use this code snippet
async function deleteCollection(db, collectionPath, batchSize) {
const collectionRef = db.collection(collectionPath);
const query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject);
});
}
async function deleteQueryBatch(db, query, resolve) {
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve();
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, resolve);
});
}
index.js

Keep getting error when trying to upload image to Firebase Storage in Flutter

The image is not uploading getting the error is "The server has terminated the upload session User does not have permission to access this object". I change my security rules of Storage but again got the same error
import 'dart:io';
class _HomeScreenState extends State<HomeScreen> {
Image? childImage;
TextEditingController childNameController = TextEditingController();
TextEditingController childAgeController = TextEditingController();
TextEditingController childDiagnosisController = TextEditingController();
GlobalKey<FormState> _formKey = GlobalKey();
FocusNode _childNameFocus = FocusNode();
FocusNode _childAgeFocus = FocusNode();
FocusNode _childDiagnosisFocus = FocusNode();
String buttonText = 'Image';
String get _childName => childNameController.text;
void _nameEditingComplete() {
final newFocus = widget.nameValidator.isValid(_childName)
? _childAgeFocus
: _childNameFocus;
FocusScope.of(context).requestFocus(newFocus);
}
Future<void> writeChildrenToDb(
String parentUid,
String childUid,
String childNameInput,
String childAgeInput,
String childDiagnosisInput,
String childPicUrl) async {
FirebaseFirestore.instance
.collection('users')
.doc(parentUid)
.collection('children')
.doc(childUid)
.set({
'childName': childNameInput,
'childAge': childAgeInput,
'childDiagnosis': childDiagnosisInput,
'childUid': childUid,
'childPicUrl': childPicUrl,
});
} // writes children details to db
Future<String> uploadImageToFirebase(String childUid, File img) async {
Reference storage = FirebaseStorage.instance
.ref()
.child('users/$parentIdGlobal/$childUid/child_pic');
UploadTask uploadTask = storage.putFile(img);
var dowurl = await (await uploadTask).ref.getDownloadURL();
var url = dowurl.toString();
return url;
}
_showAddDialog() {
String? childUid = Uuid().v4();
String? childNameInput;
String? childAgeInput;
String? childDiagnosisInput;
String? childPicUrl;
File? pickedImage;
bool imgStatus = true;
return showDialog(
context: context,
builder: (context) => StatefulBuilder(
builder: (context, setState) => AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
10.0,
),
),
title: Text(
'Add Child Information',
),
contentPadding: EdgeInsets.all(8.0),
elevation: 10.0,
content: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Here is my image path portion. My image appears in the dialogue box, but it does not print or upload to the Firebase Cloud.
GestureDetector(
onTap: () async {
await Permission.photos.request();
var status = await Permission.photos.status;
if (status.isGranted) {
XFile? _pickedImage = await ImagePicker().pickImage(
source: ImageSource.gallery,
maxWidth: 100,
maxHeight: 100,
);
if (_pickedImage != null) {
pickedImage = File(_pickedImage.path);
setState(() {
imgStatus = true;
});
}
} else if (status.isDenied ||
status.isPermanentlyDenied) {
showDialog(
context: context,
builder: (context) {
if (Platform.isAndroid)
return AlertDialog(
title: Text('Permission Not Granted'),
content: Text(
'The permission for photo library is not granted'),
actions: [
TextButton(
onPressed: () => openAppSettings(),
child: Text('Ok'),
),
],
);
return CupertinoAlertDialog(
title: Text('Permission Not Granted'),
content: Text(
'The permission for photo library is not granted'),
actions: [
TextButton(
onPressed: () => openAppSettings(),
child: Text('Ok'),
),
],
);
});
}
},
child: Padding(
padding: EdgeInsets.only(
top: 10.0,
bottom: 10.0,
),
child: Container(
height: 100.0,
width: 100.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.transparent,
border: Border.all(
style: BorderStyle.solid,
),
),
child: pickedImage == null
? Icon(
Icons.add,
color: Colors.black,
)
: Image.file(
pickedImage!,
fit: BoxFit.contain,
),
),
),
),
],
),
),
),
actions: <Widget>[
TextButton(
onPressed: () {
childNameController.clear();
childAgeController.clear();
Navigator.of(context).pop();
},
child: Text('Cancel'),
),
TextButton(
onPressed: imgStatus
?() async {
childNameInput = childNameController.text;
childAgeInput = childAgeController.text;
childDiagnosisInput = childDiagnosisController.text;
String parentUid = await getData('parentUid') ?? '';
if (_formKey.currentState?.validate() ?? true) {
if (pickedImage != null) {
childPicUrl =
await uploadImageToFirebase(childUid, pickedImage!);
}
await writeChildrenToDb(parentUid, childUid, childNameInput!,
childAgeInput!, childDiagnosisInput!, childPicUrl!);
childNameController.clear();
childAgeController.clear();
Navigator.of(context).pop();
}
}: null,
child: Text('Ok'),
),
],
),
),
);
}
security rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write
}
}
}

Flutter | How to create arounded image?

I'm trying to find a solution for resizing an image.
The images are picked from a gallery or camera. The problem that I have Is that the image always is not sharp.
This Is How I pick the photo
void _showPickOptionsDialog(BuildContext context, UserData userData) {
final user = Provider.of<Userforid>(context, listen: false);
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text("Pick From Gallery"),
onTap: () {
_loadPicker(ImageSource.gallery, userData);
Navigator.pop(context);
},
),
ListTile(
title: Text("Pick from Camera"),
onTap: () {
_loadPicker(ImageSource.camera, userData);
Navigator.pop(context);
},
),
],
),
),
);
}
Future _loadPicker(ImageSource source, UserData userData) async {
final XFile file =
await picker.pickImage(source: source, imageQuality: 100);
if (this.mounted) {
// This checks if the widget is still in the tree
setState(() {
if (file != null) {
_cropImage(file, userData);
} else {
return null;
}
});
//Navigator.pop(context);
}
}
_cropImage(XFile picked, UserData userData) async {
final user = FirebaseAuth.instance.currentUser.uid;
File cropped = await ImageCropper.cropImage(
sourcePath: picked.path,
aspectRatioPresets: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio16x9,
CropAspectRatioPreset.ratio5x4
],
maxWidth: 800,
);
if (cropped != null) {
setState(() {
_pickedImage = cropped;
});
}
if (_pickedImage != null) {
final ref = FirebaseStorage.instance
.ref()
.child('user_profile_pictures')
.child(user + '.jpg');
await ref.putFile(_pickedImage);
final url = await ref.getDownloadURL();
_curenturl = url;
await DatbaseService(uid: user).updateUserData(
...);
}
}
And this is how I display them
Container(
child: ClipRRect(
borderRadius:
BorderRadius.circular(60),
child: Container(
height: 110,
width: 110,
decoration: BoxDecoration(
color: Colors.white,
),
child: _pickedImage != null
? Image.file(
_pickedImage,
fit: BoxFit.cover,
)
: userData.url != null &&
userData.url !=
"profilepictureer"
? Image.network(
userData.url,
fit: BoxFit.cover,
)
: Image.asset(
'assets/profilepictureer.png') // Your widget is here when image is no available.
),
),
decoration: new BoxDecoration(
shape: BoxShape.circle,
border: new Border.all(
color: Colors.black,
width: 1)),
),
So the images are set as user profile photos. Probably a solution will be to upload rounded images like Instagram. So the question that I have is how can a user picks a normal photo from camera or gallery and upload it as rounded?
If not how to solve ghe problem then?
You can simply wrap the widget with a ClipOval with flutter.
Take a look at this doc: Flutter Document
or Try using BoxFit.fill
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
userData.url,
fit: BoxFit.fill,
),

Why are the picked images are not sharp?

Hey I am using a method for picking photos for user profile picture like that
void _showPickOptionsDialog(BuildContext context, UserData userData) {
final user = Provider.of<Userforid>(context, listen: false);
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text("Pick From Gallery"),
onTap: () {
_loadPicker(ImageSource.gallery, userData);
Navigator.pop(context);
},
),
ListTile(
title: Text("Pick from Camera"),
onTap: () {
_loadPicker(ImageSource.camera, userData);
Navigator.pop(context);
},
),
],
),
),
);
}
Future _loadPicker(ImageSource source, UserData userData) async {
final XFile file =
await picker.pickImage(source: source, imageQuality: 100);
if (this.mounted) {
// This checks if the widget is still in the tree
setState(() {
if (file != null) {
_cropImage(file, userData);
} else {
return null;
}
});
//Navigator.pop(context);
}
}
_cropImage(XFile picked, UserData userData) async {
final user = FirebaseAuth.instance.currentUser.uid;
File cropped = await ImageCropper.cropImage(
sourcePath: picked.path,
aspectRatioPresets: [
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio16x9,
CropAspectRatioPreset.ratio5x4
],
maxWidth: 800,
);
if (cropped != null) {
setState(() {
_pickedImage = cropped;
});
}
if (_pickedImage != null) {
final ref = FirebaseStorage.instance
.ref()
.child('user_profile_pictures')
.child(user + '.jpg');
await ref.putFile(_pickedImage);
final url = await ref.getDownloadURL();
_curenturl = url;
await DatbaseService(uid: user).updateUserData(
...);
}
}
And then I displaying the image like that
Container(
child: ClipRRect(
borderRadius:
BorderRadius.circular(60),
child: Container(
height: 110,
width: 110,
decoration: BoxDecoration(
color: Colors.white,
),
child: _pickedImage != null
? Image.file(
_pickedImage,
fit: BoxFit.cover,
)
: userData.url != null &&
userData.url !=
"profilepictureer"
? Image.network(
userData.url,
fit: BoxFit.cover,
)
: Image.asset(
'assets/profilepictureer.png') // Your widget is here when image is no available.
),
),
decoration: new BoxDecoration(
shape: BoxShape.circle,
border: new Border.all(
color: Colors.black,
width: 1)),
),
So a user picks a photo then he can choose if he wanna crop the image and then im creating a downloadurl which im uploading into cloud firestorm and finally uploading the image into firebase cloud storage.
When ever I wanna display the photo I just calling the url.
The problem that I have is that the image looks pixaled and not sharp.
Like this
Hope anyone can help.
My 2 cents
First, try downloading the image directly from the online storage to your computer to check if it was corrupted during the upload.
Next, use the CircleAvatar widget to check whether the problem is not with the displaying part.
CircleAvatar(
radius: 50.0,
backgroundImage: _pickedImage,
)

The photo does not show up with image_picker- Flutter

I cant handle with image_picker. When I select a photo, I should see the photo instead of the avatar icon, but I don't know why it doesn't work that way. I'm new in flutter and maybe it should be solved in a different way.
The orange circle should stay and the icon should change, any advice will be great for me
Widget _avatar() {
return const CircleAvatar(
radius: 83,
backgroundColor: Colors.orange,
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 80,
child: Icon(Icons.person_outline, size: 60, color: Colors.orange),
),
);
}
File? _image;
final picker = ImagePicker();
Future getImage() async {
final pickedFile = await picker.getImage(
source: ImageSource.gallery, maxWidth: 1800, maxHeight: 1800);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future getCameraImage() async {
final pickedFile = await picker.getImage(
source: ImageSource.camera,
maxWidth: 1800,
maxHeight: 1800,
);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
void _showPicker(BuildContext context) {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: new Icon(Icons.photo_size_select_large_sharp),
title: new Text('Photo Library'),
onTap: () {
getImage();
Navigator.of(context).pop();
}),
ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
getCameraImage();
Navigator.of(context).pop();
},
),
],
),
),
);
});
}
Widget _changeAvatarButton(BuildContext context) {
return Column(
children: [
CircleAvatar(
radius: 83,
backgroundColor: Colors.orange,
child: _image == null ? _avatar() : Image.file(_image!),
),
CustomButtonText(
onPressed: () {
_showPicker(context);
},
title: 'photo',
textColor: Colors.teal),
],
);
}
Change Your CircleAvtar widget with the below one and if you don't want to show the orange circle then set the backgroundColor: _image == null ? Colors.orange : Colors.transparent.
CircleAvatar(
radius: 83,
backgroundColor: Colors.orange,
child: _image == null
? _avatar()
: ClipRRect(
borderRadius: BorderRadius.circular(83),
child: Image.file(
_image!,
height: 160, // Change the size up or down accordingly border radius
width: 160, // Change the size up or down accordingly border radius
fit: BoxFit.cover,
)),
),
It looks all fine with the state update and the image picking. What you should be paying attention at is the async functions, because you need to wait for the images before updating your widgets, and getCameraImage() and getImage() are a Future. Check if adding await solves the problem.
ListTile(
leading: new Icon(Icons.photo_size_select_large_sharp),
title: new Text('Photo Library'),
onTap: () async {
await getImage();
Navigator.of(context).pop();
}),
ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () async {
await getCameraImage();
Navigator.of(context).pop();
},
),