I have an image picker function, that picks image from gallery and then assigns that to _image variable which is String. It converts it to base64 because that is what was necessary. I want to know how would I go about getting the default image from assets as the _image if no image was picked (picked image is null). Here's the code and things I've tried commented out, it is under else in code:
Future _getImage() async {
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
final file = File(pickedFile.path);
_image = Utility.base64String(file.readAsBytesSync());
} else {
//if image wasn't picked, get the default one from assets
print('No image selected.');
// final file = File(AssetImage('assets/defaultfood.jpg').toString());
// _image = Utility.base64String(file.readAsBytesSync());
//final file = File('assets/defaultfood.jpg');
//_image = Utility.base64String(file.readAsBytesSync());
}
});
}
add image placeholder like this ternary condition
child: pickedFile == null ? Image.asset("assets/images/man_user.png",height: 100, width: 100): Image.file(pickedFile, height: 100, width: 100),
Related
I have a profile screen that prompts user to enter information and there's a image picker for the profile image.
I use Uint8List to store the picked image and upload to a database.
How do I make an image in assets the default image if the user doesn't select an image?
class _SignUpScreenState extends State<SignUpScreen> {
Uint8List? _image;
#override
void dispose() {...}
void selectImage() async {
Uint8List imageFile = await pickImage(ImageSource.gallery);
setState(() {
_image = imageFile;
});
}
void signupUser() async {
final navigator = Navigator.of(context);
if (_image == null) {
//set default image as profile
showSnackBar('Please select image', context);
return;
}
setState(() {...}
My ImagePicker is as follows:
pickImage(ImageSource source) async {
final ImagePicker _imagePicker = ImagePicker();
XFile? _file = await _imagePicker.pickImage(source: source);
if (_file != null) {
return await _file.readAsBytes();
}
}
showSnackBar(String content, BuildContext context) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(content),
),
);
}
The default image is an SVG as well but I have a png too.
Simply check the null state of Unit8List variable
/// for png assets
_image == null ? Image.asset("<asset file path>") : Image.memory(_image!)
For svg image use flutter_svg package
_image == null ? SvgPicture.asset("<asset file path>") : Image.memory(_image!)
Following a tutorial for adding and saving images and getting errors for the below code, under ImagePicker, ImageSource and SelectedImage.
Future getImage() async {
var image = await ImagePicker.PickImage(source: ImageSource.camera);
setState(() {
selectedimage = image;
});
}
You need to create an instance first, then you will be able to use pickImage method.
Future getImage() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
if (image != null) {
setState(() {
selectedimage = image;
});
}
}
Fine more about image_picker
You have to be careful whenever playing with the setState() functions. This combined with how you pick the image and how you store it in the 'var' in your case could cause further trouble. To generally ease things up for further use I recommend creating a utils class, in which you would have an image picker method, just like this one:
import 'package:image_picker/image_picker.dart';
pickImage(ImageSource source) async {
final ImagePicker _imagePicker = ImagePicker();
XFile? _file = await _imagePicker.pickImage(source: source);
if (_file != null) {
return await _file.readAsBytes();
}
print('No Image Selected');
}
Afterwards, if you would like to call that in any other instance you would need something like this, though this is for a url image(I had it in hand), such as:
void selectImage() async {
Uint8List? im = await pickImage(ImageSource.gallery);
final ByteData imageData = await NetworkAssetBundle(Uri.parse(
"url for template image"))
.load("");
final Uint8List bytes = imageData.buffer.asUint8List();
// if null - use the template image
im ??= bytes;
// update state
setState(() {
_image = im!;
});
}
Hope it helped in a way.
I am using image_picker in my flutter app.
after taking a pic, i am adding it to a XFile List. but when checking the list length it is showing as null.
When I follow the route of first adding an image from gallery and then adding a image from camera then it seems to work fine. what is the correct way of adding the camera image to the list. my code is follows:
List<XFile> ? _imageFileList;
List<XFile> ? pickedFile;
XFile ? file;
void getImageFile(ImageSource source, bool multimage) async {
if(multimage) {
pickedFile = await _picker.pickMultiImage(maxWidth: double.infinity,
maxHeight: double.infinity, imageQuality: 10);
setState(() {
_imageFileList = pickedFile;
print('image selected');
Navigator.of(context).pop();
Flushbar(
message: 'length of imagelist ${_imageFileList?.length}',
duration: Duration(seconds: 5),
)..show(context);
});
} else{
file = await _picker.pickImage(
source: source, maxWidth: double.infinity,
maxHeight: double.infinity, imageQuality: 10);
setState(() {
pickedFile?.add(file!) ;
_imageFileList?.add(file!) ; //
print('camera image selected');
print('image selected');
Navigator.of(context).pop();
Flushbar(
message: 'length of imagelist ${_imageFileList?.length}',
duration: Duration(seconds: 5),
)..show(context);
});
}
Because in 'else' block you don't initialize _imageFileList. You are trying to add an item to an uninitialized list. Therefore, you can add image from camera after the gallery. Because in 'if' block it will be initialized.
There is 2 option:
List<XFile> _imageFileList = <XFile>[];
and in 'if' block: _imageFileList.addAll(pickedFile) instead of _imageFileList = pickedFile;
In 'else' block: if(_imageFileList == null) _imageFileList = <XFile>[]
In 'if' block: if(_imageFileList == null) _imageFileList = <XFile>[] and after that, _imageFileList.addAll(pickedFile)
For me, the option 1 is the best way to doing this.
I want to convert image captured with camera to base64 but it seems am converting the image path and not the image itself, please help me.
File file;
final picker = ImagePicker();
void _choose() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
file = File(pickedFile.path);
if (file != null) {
setState(() {
base64Encode(file.readAsBytesSync());
print(base64Encode(Image.file(file));
});
}
}
Wrong:
print(base64Encode(Image.file(file));
Right:
print(base64Encode(file.readAsBytesSync()));
I'm new in Flutter and can't get image_picker to open a picture from gallery.
It opens Gallery, but when I tap on a picture, just close gallery
My code is like this.. what i'm missing?
File _imagenTemporal;
var imagen;
Future getImagen(String opcion) async {
if (opcion == "camara") {
imagen = await ImagePicker.pickImage(source: ImageSource.camera);
} else if (opcion == "galeria") {
imagen = await ImagePicker.pickImage(source: ImageSource.gallery);
}
setState(() {
_imagenTemporal = imagen;
}
);
}
ImagePicker is just a FileChooser function that returns a Future<File> widget when the user selects a File from the gallery or takes a picture. You should use the returned file to construct an Image.file widget:
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: showSelectedImage();
),
Future<Image> showSelectedImage() async {
_imagenTemporal = await ImagePicker.pickImage(source: ImageSource.gallery);
return Image.file(_imageTemporal);
}