flutter image picker crashing - flutter

I am trying to use the image_picker on flutter app everything is fine until gallery open i choose the image then the app will crash and restart.
before this it was working fine like 1 month ago but now it is not. is there any solution
this is my code.
Future _pickImage() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
_image = imageTemporary;
});
} catch (error) {
print("error: $error");
}
// setState(() {
// _image = img;
// });
}
File? _image;
Future _pickImage() async {
try {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final imageTemporary = File(image.path);
setState(() {
_image = imageTemporary;
});
} catch (error) {
print("error: $error");
}
}

This code snippet can help you.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class PickImage extends StatefulWidget {
const PickImage({Key? key}) : super(key: key);
#override
State<PickImage> createState() => _PickImageState();
}
class _PickImageState extends State<PickImage> {
XFile? _image;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Column(
children: [
TextButton(
onPressed: _imageHandler, child: const Text("Pick image")),
if (_image != null) Image.file(File(_image!.path))
],
),
),
);
}
Future _imageHandler() async {
try {
final XFile? imagePicker =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (imagePicker != null) {
_image = imagePicker;
} else {
/// user canceled
}
} catch (e) {
print(e);
}
}
}

Related

How to play video that picked from image_picker using video_player flutter

How to play video that is picked from image_picker using video_player flutter.
I created a method to pick a video and display a video But the problem is I don’t know how to display a video. But this is what I got so far. It always says that the imageFile is null. Is there any to fix the problem? Please take a look at the code it’s not long.
code:
String fileName1 = '';
String path1 = '';
File? imageFile;
#override
void initState() {
loadVideoPlayer();
super.initState();
}
loadVideoPlayer() {
videoController = VideoPlayerController.file(videoFile!);
videoController.addListener(() {
setState(() {});
});
videoController.initialize().then((value) {
setState(() {});
});
}
\\To display a video
AspectRatio(
aspectRatio: videoController.value.aspectRatio,
child:VideoPlayer(videoController),
),
//Pause And Play
IconButton(
onPressed: () {
if (videoController
.value.isPlaying) {
videoController.pause();
} else {
videoController.play();
}
setState(() {});
},
icon: Icon(videoController.value.isPlaying
? Icons.pause
: Icons.play_arrow)),
//To pick video
void selectVideo() async {
final XFile? results = await picker.pickVideo(source: ImageSource.gallery);
if (results != null) {
path1 = results.path;
fileName1 = results.name.replaceFirst("image_picker", "");
setState(() {});
print(fileName1);
} else {
print('No video picked');
}
setState(() {
videoFile = File(results!.path);
});
}
Do not call the loadVideoPlayer() inside the initState but reload the player every time a video is picked :
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
#override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
VideoPlayerController? _videoPlayerController;
loadVideoPlayer(File file) {
if(_videoPlayerController != null) {
_videoPlayerController!.dispose();
}
_videoPlayerController = VideoPlayerController.file(file);
_videoPlayerController!.initialize().then((value) {
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: selectVideo,
child: Icon(
Icons.add,
),
),
body: Center(
child: Stack(
children: [
if (_videoPlayerController != null) ...[
AspectRatio(
aspectRatio: _videoPlayerController!.value.aspectRatio,
child: VideoPlayer(_videoPlayerController!),
),
]
],
),
),
);
}
void selectVideo() async {
final XFile? results =
await ImagePicker().pickVideo(source: ImageSource.gallery);
if (results != null) {
setState(() {
File file = File(results.path);
loadVideoPlayer(file);
});
} else {
print('No video picked');
}
}
}

Error :The argument type 'XFile' can't be assigned to the parameter type 'File'

I am working on a Flutter app to take image from gallery and predict the appropriate output via detection using the model I trained using Machine learning but, I am getting an error for this following code:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late bool _isLoading;
late File _image;
late List _output;
#override
void initState() {
// TODO: implement initState
super.initState();
_isLoading = true;
loadMLModel().then((value){
setState(() {
_isLoading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Brain Tumor Detection"),
),
body: _isLoading ? Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
) : SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_image == null ? Container() : Image.file(File(_image.path)),
SizedBox(height: 16,),
_output == null ? Text(""): Text(
"${_output[0]["label"]}"
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
chooseImage();
},
child: Icon(
Icons.image
),
)
,
);
}
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = image as File;
});
runModelOnImage(image);
}
runModelOnImage(File image) async{
var output = await Tflite.runModelOnImage(
path: image.path,
numResults: 2,
imageMean: 127.5,
imageStd: 127.5,
threshold: 0.5
);
setState(() {
_isLoading = false;
_output = output!;
});
}
loadMLModel() async {
await Tflite.loadModel(
model: "assets/btc.tflite",
labels: "assets/labels.txt"
);
}
}
The error is:
The argument type 'XFile' can't be assigned to the parameter type 'File'.
I have tried all the other alternatives given out there for imagepicker issues faced by other people. Any help to solve this would be great!
Thank you in advance!!
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = File(image.path);
});
runModelOnImage(_image);
}
I was facing the same issue. What I did was:
Created a variable of XFile in my widget XFile? _image;
Look at this function
Future getImageFromGallery() async {
_image = await ImagePicker()
.pickImage(source: ImageSource.gallery, maxHeight: 300, maxWidth: 300);
if (_image!.path.isNotEmpty) {
setState(() {
pickedImage = true;
});
}
}
On the press of a button, called the above function.
Used the follwing function to upload file on Firebase storage
Future uploadLogo(BuildContext? context, XFile? image) async {
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage
.ref()
.child('shops/${_name.text}/Logo${DateTime.now().toString()}');
final path = image!.path; //Getting the path of XFile
File file = File(path);// Turning that into File
UploadTask uploadTask = ref
.putFile(file); //Getting a proper reference to upload on storage
final TaskSnapshot downloadUrl = (await uploadTask); //Uploading to //storage
imageUrlShop = await downloadUrl.ref.getDownloadURL();
}
My answer is almost same as of the earlier ones but there is a little change in the format and how the argument is being passed. This is working for me. Might work for you too...
You are calling runModelOnImage which takes a File as an argument, with an XFile.
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = File(image.path);
});
runModelOnImage(_image);
}

final imageFile = await File(path); doesn't create a file

I am using the camera to take a picture and save the picture on phones memory to later send it to AWS. I can take a picture and the path for the picture is there, but I am failing to create a file from the path using:
final imageFile = await File(path);
Why is the file not being created here? I always get 'Image file does not exist' on debug console.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class CameraPage extends StatefulWidget {
// 1
final CameraDescription? camera;
// 2
final ValueChanged? didProvideImagePath;
CameraPage({Key? key, this.camera, this.didProvideImagePath})
: super(key: key);
#override
State<StatefulWidget> createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage> {
CameraController? _controller;
Future<void>? _initializeControllerFuture;
#override
void initState() {
super.initState();
// 3
_controller = CameraController(widget.camera!, ResolutionPreset.medium);
_initializeControllerFuture = _controller?.initialize();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
// 4
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(this._controller!);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
// 5
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera), onPressed: _takePicture),
);
}
// 6
void _takePicture() async {
try {
await _initializeControllerFuture;
final tmpDirectory = await getTemporaryDirectory();
final filePath = '${DateTime.now().millisecondsSinceEpoch}.jpg';
final path = join(tmpDirectory.path, filePath);
await _controller?.takePicture();
widget.didProvideImagePath!(path);
final imageFile = await File(path);
if (imageFile.existsSync())
print('Image file exists');
else
print('Image file does not exist');
} catch (e) {
print(e);
}
}
// 7
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
}
takePicture method will return taken image as XFile, you can use the XFile path to create a File with taken Image path like below code.
File? imageFile;
XFile? xFile = await _controller?.takePicture();
if (xFile != null) {
imageFile = File(xFile.path);
}
if (imageFile != null && imageFile.existsSync()) {
print('Image file exists');
} else {
print('Image file does not exist');
}

Flutter Camera recorded Video are incompatible with browsers - how to convert to .mp4?

I'm trying to capture a video and upload it to firebase storage.
The problem is, the recorded video format is .mov and this format seems to be incompatible with browsers.
How could I convert the recorded file to .mp4?
Below is the code I use to record and upload my videos.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
class CameraTestPage extends StatefulWidget {
const CameraTestPage({Key? key}) : super(key: key);
#override
_CameraTestPageState createState() => _CameraTestPageState();
}
class _CameraTestPageState extends State<CameraTestPage> {
List<CameraDescription>? cameras;
CameraController? controller;
bool frontCamera = false;
XFile? videoFile;
VideoPlayerController? videoController;
VoidCallback? videoPlayerListener;
#override
void initState() {
initCamera();
super.initState();
}
initCamera() async {
if (cameras == null) {
cameras = await availableCameras();
}
if (controller?.value.isInitialized ?? false) {
controller!.dispose();
}
controller = CameraController(
cameras!.firstWhere(
(element) => element.lensDirection == (frontCamera ? CameraLensDirection.front : CameraLensDirection.back),
),
ResolutionPreset.medium,
enableAudio: false,
);
controller!.initialize().then((value) {
setState(() {});
});
}
void onVideoRecordButtonPressed() {
startVideoRecording().then((_) {
if (mounted) setState(() {});
});
}
void onStopButtonPressed() {
stopVideoRecording().then((file) {
if (mounted) setState(() {});
if (file != null) {
print('Video recorded to ${file.path}');
videoFile = file;
_startVideoPlayer();
}
});
}
Future<void> _startVideoPlayer() async {
if (videoFile == null) {
return;
}
final VideoPlayerController vController = VideoPlayerController.file(File(videoFile!.path));
videoPlayerListener = () {
if (videoController != null && videoController!.value.size != null) {
// Refreshing the state to update video player with the correct ratio.
if (mounted) setState(() {});
videoController!.removeListener(videoPlayerListener!);
}
};
vController.addListener(videoPlayerListener!);
await vController.setLooping(true);
await vController.initialize();
await videoController?.dispose();
if (mounted) {
setState(() {
videoController = vController;
});
}
await vController.play();
}
Future<void> startVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isInitialized) {
print('Error: select a camera first.');
return;
}
if (cameraController.value.isRecordingVideo) {
// A recording is already started, do nothing.
return;
}
try {
await cameraController.startVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return;
}
}
Future<XFile?> stopVideoRecording() async {
final CameraController? cameraController = controller;
if (cameraController == null || !cameraController.value.isRecordingVideo) {
return null;
}
try {
return cameraController.stopVideoRecording();
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
}
void _showCameraException(CameraException e) {
print('Error: ${e.code}\n${e.description}');
}
_uploadVideo() async {
Reference ref = FirebaseStorage.instance.ref("test/test.mov");
UploadTask uploadTask = ref.putFile(File(videoFile!.path), SettableMetadata(contentType: 'video/mov'));
print("uploading");
uploadTask.whenComplete(() async {
String downloadUrl = await ref.getDownloadURL();
print("download url: $downloadUrl");
});
}
Widget _thumbnailWidget() {
final VideoPlayerController? localVideoController = videoController;
return Expanded(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
child: (localVideoController == null)
? Center(
child: Container(
child: Text("none"),
),
)
: Container(
child: AspectRatio(
aspectRatio: localVideoController.value.aspectRatio,
child: VideoPlayer(localVideoController),
),
decoration: BoxDecoration(
border: Border.all(color: Colors.pink),
),
),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Camera Test")),
body: Column(
children: [
if (controller != null)
Container(
child: CameraPreview(controller!),
height: 400,
),
Row(
children: [
ElevatedButton(
onPressed: () {
frontCamera = !frontCamera;
initCamera();
},
child: Text("Switch"),
),
ElevatedButton(
onPressed: () {
controller?.value.isRecordingVideo ?? false ? onStopButtonPressed() : onVideoRecordButtonPressed();
},
child: Text(controller?.value.isRecordingVideo ?? false ? "Stop" : "Record"),
),
ElevatedButton(
onPressed: videoFile != null ? _uploadVideo : null,
child: Text("Upload video"),
),
],
),
_thumbnailWidget(),
],
),
);
}
}
You can use the video_compress package to convert the video to mp4.
Here is your _uploadVideo() method updated to include this:
_uploadVideo() async {
Reference ref = FirebaseStorage.instance.ref("test/test.mp4");
MediaInfo? mediaInfo = await VideoCompress.compressVideo(
videoFile!.path,
quality: VideoQuality.DefaultQuality,
deleteOrigin: false, // It's false by default
);
UploadTask uploadTask = ref.putFile(
File(mediaInfo!.path!), SettableMetadata(contentType: 'video/mp4'));
print("uploading");
uploadTask.whenComplete(() async {
String downloadUrl = await ref.getDownloadURL();
print("download url: $downloadUrl");
});
}
Ensure you import the package by including this line:
import 'package:video_compress/video_compress.dart';

Cannot load image with flutter image_editor_pro

I want to use this package. But I seem to be missing something. This is my code:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _image = File("assets/images/butterfly.jpg");
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
error: Cannot open file, path = 'assets/images/butterfly.jpg' (OS Error: No such file or directory, errno = 2).
How am I supposed to load an image with this?
I even tried to use Image from the get go. But no result. Maybe I am doing the File to Image conversion wrong?
**Update 1: **
class _HomePageState extends State<HomePage> {
final image = Image.asset('assets/images/butterfly.jpg');
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
image = geteditimage; // shows error asking to make the field not final
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(image).toCenter()) //The argument type 'Image' can't be assigned to the parameter type 'File'.
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
You need to add your asset directories to your pubspec.yaml.
For example:
dependencies:
...
dev_dependencies:
...
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
Then you can read the file as an image like so:
final image = Image.asset('assets/images/butterfly.jpg');
If you need to read the image as a file for the package you are trying to use, instead of coding in images, use a package like image_picker.
For your case:
class _HomePageState extends State<HomePage> {
File _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
Solution for this is error is to prevent the Image.file to read from null by setting a null check:
_image == null ? Container() : Image.file(_image).toCenter())
The app will build without error, and after that you can use the image editor pro to edit your image.
If anyone wants to pass image to editor page from image picker :
make changes to image_editor_pro.dart file
final Color appBarColor;
final Color bottomBarColor;
final Directory pathSave;
final double pixelRatio;
final File image;
ImageEditorPro(
{this.appBarColor,
this.bottomBarColor,
this.pathSave,
this.pixelRatio,
this.image});
#override
void initState() {
timers();
_controller.clear();
type.clear();
// fontsize.clear();
offsets.clear();
// multiwidget.clear();
howmuchwidgetis = 0;
_image = widget.image;
super.initState();
}
**Then use this code **
import 'package:flutter/material.dart';
import 'dart:io';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_editor_pro/image_editor_pro.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:firexcode/firexcode.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
// ignore: unnecessary_null_comparison
if (pickedFile != null) {
_image = File(pickedFile.path);
print("images : $_image");
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() async {
// ignore: unused_local_variable
final geteditimage =
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
image: _image,
);
})).then((geteditimage) {
print("image : $geteditimage");
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
}
#override
Widget build(BuildContext context) {
return condition(
// ignore: unnecessary_null_comparison
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse:
// ignore: unnecessary_null_comparison
_image == null ? Container() : Image.file(_image!).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTabText().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red))
.xRaisedButton(onPressed: () {
getimageditor();
});
}
}
Widget? condition({required bool condtion, Widget? isTrue, Widget? isFalse}) {
return condtion ? isTrue : isFalse;
}