how to convert an Xfile to file? - flutter

I want to get picutres with the emulator's camera and when i take one it' doesn't save the picture and give me an error that says pickImage method reurns a Future of type XFile and I want a return of type File and when i use (as File) it give me another Error that says Xfile is not a subtype of type File
class ImageInput extends StatefulWidget {
final Function? onSelect;
const ImageInput({Key? key, this.onSelect}) : super(key: key);
#override
_ImageInputState createState() => _ImageInputState();
}
class _ImageInputState extends State<ImageInput> {
File? _imagePicker;
Future<void> _takeAPicture() async {
final picker = ImagePicker();
final imageFile = await picker.pickImage(
source: ImageSource.gallery,
maxWidth: 600,
);
}
Future<void> _chooseAPicture() async {
final picker = ImagePicker();
final imageFile = await picker.pickImage(
source: ImageSource.camera,
maxWidth: 600,
) as File;
setState(() {
_imagePicker = File(imageFile.path);
});
final appdir = await syspath.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage = await imageFile.copy('${appdir.path}/${fileName}');
widget.onSelect!(savedImage);
}
#override
Widget build(BuildContext context) {
return Row(children: [
Container(
child: _imagePicker != null
? Image.file(
_imagePicker as File,
fit: BoxFit.cover,
width: double.infinity,
)
: Text(
'No Image Taken',
textAlign: TextAlign.center,
),
alignment: Alignment.center,
height: 100,
width: 100,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1),
),
),
SizedBox(
height: 10,
),
Expanded(
child: Column(
children: [
TextButton.icon(
onPressed: () => _takeAPicture(),
label: Text('choose an Image'),
style: ButtonStyle(
textStyle: MaterialStateProperty.all(
TextStyle(color: Theme.of(context).primaryColor),
),
),
icon: Icon(Icons.camera),
),
TextButton.icon(
onPressed: () => _chooseAPicture(),
label: Text('Take an Image'),
style: ButtonStyle(
textStyle: MaterialStateProperty.all(
TextStyle(color: Theme.of(context).primaryColor),
),
),
icon: Icon(Icons.camera_enhance_sharp),
),
],
),
),
]);
}
}

Try out below code for XFile
final ImagePicker _picker = ImagePicker();
Future getForFrontImage(ImageSource source) async {
final XFile? pickedFile = await _picker.pickImage(source: source);
if (pickedFile != null) {
setState(() {
selectedChequeImg = File(pickedFile.path);
});
}
}

Related

How can I use the ImagePicker library's pickImage function in this code to replace the deprecated getImage method?

How can I use the ImagePicker library's pickImage function in this code to replace the deprecated getImage method?How can I replace the deprecated getImage method in Flutter's Image Picker package with the pickImage method from the latest version of the package?
I am currently using the Image Picker package in my Flutter app and I recently received an error saying that the getImage method I was using has been deprecated. I've learned that it has been replaced by the pickImage method, but I'm not sure how to make the necessary changes to my code.
import 'dart:async';
import 'dart:io';
import 'package:farmassist/app_theme.dart';
import 'package:farmassist/data/diseases/classifier.dart';
import 'package:farmassist/data/diseases/disease_detection_model.dart';
import 'package:farmassist/ui/diseases/diagnosis.dart';
import 'package:flutter/material.dart';
import 'package:image/image.dart' as img;
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:tflite_flutter_helper/tflite_flutter_helper.dart';
class ViewImageRegion extends StatefulWidget {
const ViewImageRegion({#required this.diagnosis});
final Diagnosis diagnosis;
#override
_ViewImageRegionState createState() => _ViewImageRegionState();
}
class _ViewImageRegionState extends State<ViewImageRegion> {
PickedFile _image;
File plantImage;
dynamic _pickImageError;
Classifier _classifier;
var logger = Logger();
Category _category;
void _onImageButtonPressed(ImageSource source, {BuildContext context}) async {
try {
final pickedFile = await ImagePicker().getImage(source: source);
_image = pickedFile;
final File _plantImage = File(_image.path);
File croppedFile = await ImageCropper.cropImage(
sourcePath: _plantImage.path,
aspectRatioPresets: [
CropAspectRatioPreset.square,
CropAspectRatioPreset.ratio3x2,
CropAspectRatioPreset.original,
CropAspectRatioPreset.ratio4x3,
CropAspectRatioPreset.ratio16x9,
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Cropper',
toolbarColor: Colors.deepOrange,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.original,
lockAspectRatio: false,
),
iosUiSettings: IOSUiSettings(minimumAspectRatio: 1.0),
);
plantImage = croppedFile;
_predict(_plantImage);
} catch (e) {
setState(() {
_pickImageError = e;
});
}
}
#override
void initState() {
super.initState();
_classifier = DiseaseDetectionModel();
}
void _predict(File image) async {
img.Image imageInput = img.decodeImage(image.readAsBytesSync());
var prediction = _classifier.predict(imageInput);
setState(() {
this._category = prediction;
});
if (_category.score > 0.5) {
Future.delayed(
Duration.zero,
() => widget.diagnosis.update(
_category.label, (_category.score * 100).toStringAsFixed(2)),
);
} else {
Future.delayed(
Duration.zero,
() => widget.diagnosis.update('Healthy', null),
);
}
}
void _cancelImage() {
setState(() {
plantImage = null;
});
Future.delayed(
Duration.zero,
() => widget.diagnosis.update('Disease', null),
);
}
#override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Column(
children: <Widget>[
Container(
height: 224.0,
width: 224.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 20),
borderRadius: BorderRadius.circular(18),
color: Colors.white,
),
child: Center(
child: plantImage == null
? Text(
'No image selected',
textAlign: TextAlign.center,
style: AppTheme.bodyText1,
)
: Image.file(
plantImage,
height: 224.0,
width: 225.0,
fit: BoxFit.fill,
),
),
),
Container(
height: 90.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton(
Icon(Icons.add_a_photo_outlined),
() => _onImageButtonPressed(
ImageSource.camera,
context: context,
),
),
_buildButton(
Icon(Icons.image_outlined),
() => _onImageButtonPressed(
ImageSource.gallery,
context: context,
),
),
_buildButton(
Icon(Icons.image_not_supported_outlined),
() => _cancelImage(),
),
],
),
),
],
),
),
);
}
Widget _buildButton(Icon icon, VoidCallback callback) {
return ClipOval(
child: Material(
color: Colors.white,
child: InkWell(
splashColor: Colors.lightGreenAccent[100],
child: SizedBox(
width: 56,
height: 56,
child: icon,
),
onTap: callback,
),
),
);
}
}
i am new to flutter, so I do not know how to go about it.

Flutter - how to compress an image

I am trying to compress image that is picked via file_picker package. I am compressing image with flutter_native_image. But image is not being compressed.
Where have I gone wrong?
P.S - I can't use image_picker package because it stopped working and I had to switch to file_picker.
class UploadSingleImageToFirestore extends StatefulWidget {
const UploadSingleImageToFirestore({super.key});
#override
State<UploadSingleImageToFirestore> createState() =>
_UploadSingleImageToFirestoreState();
}
class _UploadSingleImageToFirestoreState
extends State<UploadSingleImageToFirestore> {
File? _pickedImage;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarTitle(context, 'Upload Single Image'),
backgroundColor: ZayyanColorTheme.zayyanGrey,
body: _pickedImage != null
? Center(
child: Column(
children: [
ANPFormContainer(
fieldTitle: 'Single Image',
subTitle: 'Pick Single Image',
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 140),
child: Image.file(
File(_pickedImage!.path),
height: 300,
width: 300,
),
),
),
addVerticalSpacer(25),
ElevatedButton(
onPressed: () => pickImage(),
child: const Text('Pick Image')),
ElevatedButton(
onPressed: () => _updateMedia(),
child: const Text('Upload Images')),
],
),
)
: InkWell(
onTap: () => pickImage(),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(Icons.add_a_photo),
SizedBox(height: 10),
Text('Tap anywhere to pick images')
],
),
),
),
);
}
pickImage() async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(type: FileType.image);
if (result != null) {
File file = File(result.files.single.path!);
print(file);
compressImage(file);
setState(() {
_pickedImage = file;
});
} else {
print("No file selected");
}
}
compressImage(path) async {
if (_pickedImage == null) return;
File compressedFile = await FlutterNativeImage.compressImage(
path,
quality: 10,
percentage: 20,
targetWidth: 600,
);
return compressedFile;
}
_updateMedia() async {
CollectionReference collectionRef =
FirebaseFirestore.instance.collection('Users');
final coverUrl = await context
.read<FirebaseStorageService>()
.saveCoverInCloudStorage(
file: _pickedImage!,
state: 'Test State',
township: 'Test Township',
propertyType: 'Test House',
propertyid: 'HYG-1234');
return collectionRef
.doc('gMH1s0XUIvWdD2fYfqMvPc915a03')
.update({
'logo': coverUrl,
})
.then((value) => ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Property Info Updated'))))
.catchError((error) => ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('+++ Failed to update user: $error"'))));
}
}
If your requirement is just images, Use image_picker instead of file_picker.
Fetching from image picker
You can use the built in imaqeQuality property from ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the original image quality.
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 25,
);
setState(() {
_image = image;
});
}
Use flutter_native_image to compress
Future<File> compressFile(File file) async{
File compressedFile = await FlutterNativeImage.compressImage(file.path,
quality: 5,);
return compressedFile;
}
Also Refer: Flutter the best way to compress image

Unable to fill the CircleAvatar with the selected image from image_picker

I'm getting the image from the image_picker package and loading the image in CircleAvatar but image is not filling across the circle. I have used boxfit.fill in the ClipRRect and also in the ClipOval.
import 'package:image_picker/image_picker.dart';
class EditProfileScreen extends StatefulWidget {
static const String routename = "/EditProfileScreen";
const EditProfileScreen({Key? key}) : super(key: key);
#override
_EditProfileScreenState createState() => _EditProfileScreenState();
}
class _EditProfileScreenState extends BaseState<EditProfileScreen> {
final ImagePicker _picker = ImagePicker();
XFile? _imageFileSelected;
set _imageFile(XFile? value) {
_imageFileSelected = value == null ? null : value;
}
void _onImageButtonPressed(ImageSource source,
{BuildContext? context, bool isMultiImage = false}) async {
try {
final pickedFile = await _picker.pickImage(
source: source, maxHeight: 160, maxWidth: 200);
setState(() {
_imageFile = pickedFile;
});
} catch (e) {
setState(() {
_pickImageError = e;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppWidgets.backgroundColor,
appBar: AppWidgets.appbar(text: "Edit Profile", actionWidgets: []),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.fromLTRB(20, 16, 20, 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Column(
children: [
CircleAvatar(
child: ClipRRect(
borderRadius: BorderRadius.circular(48),
child: (_imageFileSelected?.path == null)
? Image.network(
profileImagePath,
)
: Image.file(
File(_imageFileSelected!.path),
),
),
radius: 50.0,
),
SizedBox(
height: 10,
),
TextButton(
onPressed: () {
_onImageButtonPressed(ImageSource.gallery,
context: context);
},
child: AppWidgets.text(
string: 'Change Photo',
weight: FontWeight.w500,
textColor: AppWidgets.buttonColor,
size: 16),
),
],
),
),
),
);
}
Note:
I have used boxfit no luck.
I tried clipoval in the child didn't work.
I tried to put images in backgroundImage and foregroundImage unable to do
Instead of using circleavatar you can use Container with background property Try this code.
Container(
height: 88.5.h,
width: 88.5.w,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: CachedNetworkImageProvider(
state.details["profile_photo"]),
shape: BoxShape.circle,
border: Border.all(
color: ColorConstant.buttonColor,
width: 5.w)),
),
I use this to store the updated picture locally.
ps. this already has a picture which can be changed but you can just use background color to hold instead.
File _image;
String _imagepath;
Future _getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
if (image != null) {
var cropped = await ImageCropper.cropImage(
sourcePath: image.path,
maxHeight: 100,
maxWidth: 100,
aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),
cropStyle: CropStyle.circle,
compressQuality: 100,
);
this.setState(() {
_image = cropped;
});
saveImage(_image.path);
}
}
void saveImage(path) async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
saveimage.setString('imagepath', path);
}
void LoadImage() async {
SharedPreferences saveimage = await SharedPreferences.getInstance();
setState(() {
_imagepath = saveimage.getString('imagepath');
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
LoadImage();
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _getImage,
child: Container(
//padding: EdgeInsets.all(2),
decoration: BoxDecoration(
border: Border.all(
color: Colors.white,
width: 5.0,
),
shape: BoxShape.circle,
),
child: _imagepath != null
? CircleAvatar(
backgroundImage: FileImage(File(_imagepath)),
radius: 60,
)
: CircleAvatar(
backgroundImage: _image != null
? FileImage(_image)
: AssetImage('assets/mypic1.jpg'),
backgroundColor: Colors.blue[200],
radius: 60,
),
),
);

Tap on Android camera Flutter driver

Im doing an integration test in Flutter and in the application I open the camera, but I don't know how to tap on the button to do the photo, anyone know how can I search for this button?
Here is the code if the app where you can choose between pic a photo with the camera or choose one picture of your gallery
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
import 'package:random_string/random_string.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:rosita/language/firebase_remote.dart';
import 'package:rosita/api/api_provider.dart';
import 'package:rosita/constants/common.dart';
import 'package:rosita/model/image_object.dart';
import 'package:rosita/model/senior_user.dart';
import 'package:rosita/modules/widgets/button_ui.dart';
import 'package:rosita/rosita.dart';
class AddProfileImageScreen extends StatefulWidget {
const AddProfileImageScreen({Key key, this.seniorUser}) : super(key: key);
final SeniorUser seniorUser;
#override
_AddProfileImageScreenState createState() => _AddProfileImageScreenState();
}
class _AddProfileImageScreenState extends State<AddProfileImageScreen> {
bool _isProcessing = false;
File _image;
bool _enableButton = false;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
body: ModalProgressHUD(
inAsyncCall: _isProcessing,
color: Colors.transparent,
progressIndicator: const CircularProgressIndicator(
strokeWidth: 2.0,
),
child: Container(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height,
minWidth: MediaQuery.of(context).size.width),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
darkSubtitleText('choose_profile_picture', context),
Expanded(
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: Card(
shape: RoundedRectangleBorder(
side: const BorderSide(
color: AppTheme.purpleColor,
width: 4,
),
borderRadius: BorderRadius.circular(60.0),
),
elevation: 0,
color: Theme.of(context).dividerColor,
child: _image == null
? (widget.seniorUser != null &&
widget.seniorUser.profileImage != null &&
widget.seniorUser.profileImage.imageUrl !=
'')
? CachedNetworkImage(
imageUrl:
widget.seniorUser.profileImage.imageUrl,
placeholder:
(BuildContext context, String url) =>
Image.asset(ConstantsData.appIcon),
errorWidget: (BuildContext context,
String url, error) =>
const Icon(Icons.error),
fit: BoxFit.cover,
)
: Image.asset(ConstantsData.appIcon)
: Image.file(_image),
),
),
),
),
ButtonUI(
buttonName: 'ProfilePhotoFromCameraButton',
key: const Key(Keys.cameraButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('take_a_photo_with_your_camera'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: false);
},
),
verticalSpacer(),
ButtonUI(
buttonName: 'ProfilePhotoFromGalleryButton',
key: const Key(Keys.galleryButton),
isTrack: true,
color: AppTheme.primaryColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('choose_from_gallery'),
textAlign: TextAlign.center,
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
getImage(isGallery: true);
},
),
verticalSpacer(),
if (_image != null || _enableButton)
ButtonUI(
buttonName: 'ProfilePhotoUploadButton',
key: const Key(Keys.uploadButton),
isTrack: true,
color: AppTheme.purpleColor,
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
FireText.of('continue_txt'),
style: Theme.of(context)
.primaryTextTheme
.subtitle2
.copyWith(
color: Theme.of(context).backgroundColor,
),
),
),
),
onTap: () {
_uploadAllInformation();
},
),
],
),
),
),
),
);
}
Future<void> getImage({bool isGallery = true}) async {
await <Permission>[Permission.camera, Permission.storage].request();
if (await Permission.storage.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
if (!isGallery &&
await Permission.camera.status != PermissionStatus.granted) {
setState(() {
_enableButton = true;
});
return;
}
final image = await ImagePicker.pickImage(
source: isGallery ? ImageSource.gallery : ImageSource.camera);
if (image == null) return;
final cropimage = await cropImage(image);
if (cropimage == null) return;
setState(() {
_image = cropimage;
});
}
Future<File> cropImage(File imageFile) async {
final croppedFile = await ImageCropper.cropImage(
androidUiSettings: AndroidUiSettings(
statusBarColor: Theme.of(context).primaryColor,
toolbarColor: Theme.of(context).primaryColor,
toolbarWidgetColor: Theme.of(context).backgroundColor,
),
sourcePath: imageFile.path,
cropStyle: CropStyle.circle,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
maxWidth: 420,
maxHeight: 420,
);
return croppedFile;
}
Future<void> _uploadAllInformation() async {
setState(() {
_isProcessing = true;
});
widget.seniorUser.documentId =
(await FirebaseAuth.instance.currentUser()).uid;
widget.seniorUser.referralCode =
'RO-' + randomAlphaNumeric(8).toUpperCase();
widget.seniorUser.enterReferralCode = deepLinkReferralCode;
await ApiProvider().createSeniorUserProfile(widget.seniorUser);
endRegister = true;
if (!_enableButton) {
final imageData = await updateProfilePic(widget.seniorUser);
await ApiProvider()
.updateRositaProfileImage(imageData, widget.seniorUser.documentId);
}
setState(() {
_isProcessing = false;
});
Rosita.restartApp(context);
}
Future<ImageObject> updateProfilePic(SeniorUser user) async {
final imagename = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg';
final url = await ApiProvider()
.updateProfilePic('rositapics/${user.documentId}/' + imagename, _image);
final profileImage = ImageObject();
profileImage.imageUrl = url.toString();
profileImage.firebaseStoregPath =
'rositapics/${user.documentId}/' + imagename;
profileImage.imageName = imagename;
return profileImage;
}
}

Image is not getting Updated even after using setState In Flutter

I'm Using ImagePicker and ImageCropper Package to pick and crop an image from the gallery or by capturing using a camera. Everything is working fine but the Picked image is not updating on UI even after using the SetState method. When I press the button for image Selection Again Previously selected Image Appears on the UI. I have no Idea what Is causing this delay.
My ImageProcessing Class Code
class ImageProcess{
File _image, croppedFile;
final picker = ImagePicker();
//Getting Image From Gallery Or Camera.
File getImage(BuildContext context) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15))),
content: Container(
height: 250,
width: 250,
child: Row(
children: [
IconButton(
iconSize: 100,
icon: Icon(Icons.insert_photo),
onPressed: () async {
final pickedFile = await picker.getImage(
source: ImageSource.gallery,imageQuality: 20);
_image = File(pickedFile.path);
croppedFile = await _cropImage();
Navigator.of(context).pop(true);
}),
IconButton(
iconSize: 100,
icon: Icon(Icons.camera),
onPressed: () async {
final pickedFile =
await picker.getImage(source: ImageSource.camera,imageQuality: 20);
_image = File(pickedFile.path);
croppedFile = await _cropImage();
Navigator.of(context).pop(true);
})
],
)),
);
});
return croppedFile;
}
//Cropping image which has been retrieved from gallery or gallery.
Future<File> _cropImage() async {
return await ImageCropper.cropImage(
sourcePath: _image.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
]
: [
CropAspectRatioPreset.square,
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Product Image Cropper',
toolbarColor: kDarkYellow,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.square,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Product Image Cropper',
));
}
}
Ui code
class AddItem extends StatefulWidget {
#override
_AddItemState createState() => _AddItemState();
}
class _AddItemState extends State<AddItem> {
File croppedFile;
ImageProcess im = new ImageProcess();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: kVeryDarkBlue,
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.fromLTRB(20, 20, 20, 0),
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * 0.15,
width: MediaQuery.of(context).size.height * 0.15,
child: croppedFile == null
? ClipOval(
child:
Image.asset('assets/images/image.png'))
: ClipOval(child: Image.file(croppedFile))),
RaisedButton(onPressed: () {
croppedFile= im.getImage(context);
setState(() {
});
},child: Text('Press'),)
],
),
))),
);
}
}
I have tried every possible solution which came Into My mind.
Add Future in your getImage Method with some adjusts.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: AddItem(),
);
}
}
class AddItem extends StatefulWidget {
#override
_AddItemState createState() => _AddItemState();
}
class _AddItemState extends State<AddItem> {
File croppedFile;
ImageProcess im = new ImageProcess();
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.blue,
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.fromLTRB(20, 20, 20, 0),
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * 0.15,
width: MediaQuery.of(context).size.height * 0.15,
child: croppedFile == null
? ClipOval(
child: Image.asset('assets/images/image.png'))
: ClipOval(child: Image.file(croppedFile))),
RaisedButton(
onPressed: () async {
// Add await here
croppedFile = await im.getImage(context);
setState(() {});
},
child: Text('Press'),
)
],
),
))),
);
}
}
class ImageProcess {
File _image, croppedFile;
final picker = ImagePicker();
//Getting Image From Gallery Or Camera.
// now getImage is a future that wait for your choice.
Future<File> getImage(BuildContext context) async {
return await showDialog(
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15))),
content: Container(
height: 250,
width: 250,
child: Row(
children: [
IconButton(
iconSize: 100,
icon: Icon(Icons.insert_photo),
onPressed: () async {
final pickedFile = await picker.getImage(
source: ImageSource.gallery, imageQuality: 20);
_image = File(pickedFile.path);
croppedFile = await _cropImage();
// croppedFile is the return of your ShowDialog
Navigator.of(context).pop(croppedFile);
}),
IconButton(
iconSize: 100,
icon: Icon(Icons.camera),
onPressed: () async {
final pickedFile = await picker.getImage(
source: ImageSource.camera, imageQuality: 20);
_image = File(pickedFile.path);
croppedFile = await _cropImage();
// croppedFile is the return of your ShowDialog
Navigator.of(context).pop(croppedFile);
})
],
)),
);
});
}
//Cropping image which has been retrieved from gallery or gallery.
Future<File> _cropImage() async {
return await ImageCropper.cropImage(
sourcePath: _image.path,
aspectRatioPresets: Platform.isAndroid
? [
CropAspectRatioPreset.square,
]
: [
CropAspectRatioPreset.square,
],
androidUiSettings: AndroidUiSettings(
toolbarTitle: 'Product Image Cropper',
toolbarColor: Colors.yellow,
toolbarWidgetColor: Colors.white,
initAspectRatio: CropAspectRatioPreset.square,
lockAspectRatio: false),
iosUiSettings: IOSUiSettings(
title: 'Product Image Cropper',
));
}
}
After Tweaking Some Lines of I have figured Out Where Was the Problem.
Code For RaisedButton In UI
RaisedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.all(Radius.circular(15))),
content: Container(
height: 250,
width: 250,
child: Row(
children: [
IconButton(
iconSize: 100,
icon: Icon(Icons.insert_photo),
onPressed: () async {
croppedFile =
await im.getImageGallery();
setState(() {});
Navigator.pop(context);
}),
IconButton(
iconSize: 100,
icon: Icon(Icons.camera),
onPressed: () async {
croppedFile =
await im.getImageCamera();
setState(() {});
Navigator.pop(context);
})
],
)),
);
});
},
child: Text('Press'),
)
Code For ImageProcessing Class. I have Divided Large Function Into Two Sub Functions.
//Getting Image From Camera.
Future<File> getImageCamera() async{
final pickedFile = await picker.getImage(
source: ImageSource.camera,imageQuality: 20);
_image = File(pickedFile.path);
return _cropImage();
}
//Getting Image From Gallery
Future<File> getImageGallery() async{
final pickedFile = await picker.getImage(
source: ImageSource.gallery,imageQuality: 20);
_image = File(pickedFile.path);
return _cropImage();
}