Flutter can't seem to find a Json file from relative path - flutter

I apologise in advance if this is a silly question, but I have created a file and stored it in my "assets" sub-directory, which is at the same level as my lib directory and my pubspec.yaml file. I've set the relative path to "assets/ExerData.json" in my code (see below).
When I run the code saved as a scratch.dart file as shown below, hitched up to a Galaxy Nexus API 29 emulator, it can only tell me "Can't find file!"
import 'dart:io';
import 'package:flutter/services.dart';
String filePath = "assets/ExerData.json";
void main() {
performTasks();
}
void performTasks() {
if (checkFileExists(filePath)) {
readFile(filePath);
} else {
print("Can't find file");
}
}
bool checkFileExists(path) {
bool result = File(path).existsSync();
print(result.toString());
return result;
}
Future<String> readFile(path) async {
return await rootBundle.loadString(filePath);
}
I populated my pubspec.yaml file with this entry:
assets:
- assets/ExerData.json
I expected it to find my file, read it using rootbundle.loadstring(path), and print out the resulting string to the console.
As I say, all it did was print "Can't find file".
I'd very much appreciate you help on this one!
Thanks in advance!

The rootBundle contains the resources that were packaged with the app when it was built. All files specified under assets: in your pubspec are packaged with the app. You can check if file exists by wrapping rootBundle.loadString() inside try{} catch(){} block.
Future<bool> fileExists(String path) async {
try {
await rootBundle.loadString(path);
} catch (_) {
return false;
}
return true;
}
or
Future<String?> loadFile(String path) async {
try {
return await rootBundle.loadString(path);
} catch (_) {
// File not found Exception
return null;
}
}
File is a dart class. It needs absolute or relative path of the file being read.
You can use File with path_provider to get the absolute path from the current File System.
For example on Android:
Future<void> getPath() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
print('PATH IS : $appDocPath');
}
prints
'/data/user/0/com.soliev.file_demo/app_flutter'

Use:
String data = await DefaultAssetBundle.of(context).loadString("assets/ExerData.json");
final jsonResult = jsonDecode(data);
Reference: How to load JSON assets into a Flutter App?

As it turns out, the program logic had not completed initializing the necessary binding.
I called the method WidgetsFlutterBinding.ensureInitialized() in the first line of the main class and everything started working as I expected.
Thanks to everyone who looked at my question!
Here's a similar question involving binding with XML files:
How to read XML files in flutter?

Related

How can I save a file to a user specific directory flutter Desktop?

How can I allow the user to save a file to a specific folder in Flutter?
I have built a simple desktop app for Mac that returns a file from an API.
Currently, it saves the file to a caches directory.
try {
io.Directory saveDir = await getTemporaryDirectory();
String filePath = saveDir.path;
io.File returnedFile = new io.File('$filePath/$filename.xlsx');
await returnedFile.writeAsBytes(result.bodyBytes);
print(saveDir);
} catch (e) {
print(e);
}
I played around with my original code and that provided by #Pavel and managed to write my solution to saving files to a custom user-picked directory in this fashion.
The first part opens a file picker dialogue that returns a path to a directory.
The second part provides the path to the File class that then writes the file to that directory.
Hope this helps anyone trying to save files.
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Save Your File to desired location',
fileName: filename);
try {
io.File returnedFile = io.File('$outputFile');
await returnedFile.writeAsBytes(responsefile.bodyBytes);
} catch (e) {}
Use https://pub.dev/packages/file_picker
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Please select an output file:',
fileName: 'output-file.pdf',
);
if (outputFile == null) {
// User canceled the picker
}

How to record a video with Camera Plugin in flutter?

I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :
FlatButton(
onPressed: () => {
!isRecording
? {
setState(() {
isRecording = true;
}),
cameraController.prepareForVideoRecording(),
cameraController.startVideoRecording('assets/Videos/test.mp4')
}
: cameraController.stopVideoRecording(),
},
............
but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)).
I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?
In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.
You are trying to save a video in your assets folder which is not possible ,
What you need to do is to save to device locally either common folders like downloads or app directory.
Here is an example of how to go about it
dependencies:
path_provider:
Flutter plugin for getting commonly used locations on host platform
file systems, such as the temp and app data directories.
We will be saving the video to app directory.
We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider
Future<String> _startVideoRecording() async {
if (!controller.value.isInitialized) {
return null;
}
// Do nothing if a recording is on progress
if (controller.value.isRecordingVideo) {
return null;
}
//get storage path
final Directory appDirectory = await getApplicationDocumentsDirectory();
final String videoDirectory = '${appDirectory.path}/Videos';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final String filePath = '$videoDirectory/${currentTime}.mp4';
try {
await controller.startVideoRecording(filePath);
videoPath = filePath;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//gives you path of where the video was stored
return filePath;
}

Flutter: Custom name for screenshot image

I am following the following flutter package to take a screenshot of my one app page:
https://pub.dev/packages/screenshot
I have successfully implemented the example and I can see my screenshots in the gallery.
My issue is that I would like to be able to NAME those images when they are stored in the gallery using some sort of numbering system. e.g. INV_0001, INV_0002.
Is there a way to do this in code? I have the following code that successfully takes the screenshot, but does not rename the file.
CODE
_imageGallerySaver() async {
final directory = (await getApplicationDocumentsDirectory()).path; //from path_provide package
String fileName = "Bob";
String pathName = '$directory/$fileName.png';
//print(path);
screenshotController
.capture(
path: pathName,
).then((File image) async {
print("image: $image");
setState(() {
_imageFile = image;
});
print(pathName);
final result =
await ImageGallerySaver.saveImage(image.readAsBytesSync());
print("File Saved to Gallery. result: $result");
//print("path: $path");
}).catchError((onError) {
print(onError);
});
}
SNIPPET
print("File Saved to Gallery. result: $result");
results in the following output:
File Saved to Gallery. result: file:///storage/emulated/0/app_name/1581602261670.png
I would like to rename the "1581602261670" part, if possible. Thank you
In your code, you are passing that file name to construct the path, then why not change the name there itself.
Anyway, you can rename an existing file using
await file.rename (newPath
):
Can't rename files using this method. Need to use a package called Gallery Saver:
https://pub.dev/packages/gallery_saver
This package allows you to set your own file name and save to the gallery.

Flutter how to Convert filePath from content://media/external/images/media/5275 to /storage/emulated/0/DCIM/Camera/IMG_00124.jpg

I have URI LIKE below
content://media/external/images/media/5275
but I want convert it to Like format below:
/storage/emulated/0/DCIM/Camera/IMG_00124.jpg
Anyone who can help me!
Sreng Bona
Thanks!
var path = await FlutterAbsolutePath.getAbsolutePath("content://media/external/images/media/5275");
Add this flutter_absolute_path: ^1.0.6 to your file: pubspec.yaml
It will be working as Well.
Bona SR.
I had to search a lot, but I found a very useful solution to save the image in the cell phone's photo gallery and get the absolute path to use it the way you want.
For this example I used a result obtained from saving an image in the photo gallery, however it could also work to read other files, obviously making the changes that you see necessary, I hope it will help you
uri_to_file
image_gallery_saver
import 'dart:io';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:uri_to_file/uri_to_file.dart';
Future<File> saveImage(File image, String identifier) async {
try {
var result = await
ImageGallerySaver.saveImage(image.readAsBytesSync(),
quality: 60, name: identifier +
"-${DateTime.now().toIso8601String()}");
print(result);
File file = await toFile(Uri.parse(result['filePath']));
print(file);
return file;
} catch (e) {
print(e);
return new File('assets/img/default-img.jpg');
}
}
// example
saveImage(File("path/image.jpg"),"img-test");

Flutter: How to convert URI to File?

I want to convert path "content://media/external/images/media/138501" to File and set in the Image.
Code:
File imageFile = File("content://media/external/images/media/138501");
is not working on:
DecorationImage(image: ExactAssetImage(imageFile.path),fit: BoxFit.fill)
You can use uri_to_file package. It supports content:// URI.
Simple to use (Updated)
import 'package:uri_to_file/uri_to_file.dart';
try {
String uriString = 'content://sample.txt';
// Don't pass uri parameter using [Uri] object via uri.toString().
// Because uri.toString() changes the string to lowercase which causes this package to misbehave
// If you are using uni_links package for deep linking purpose.
// Pass the uri string using getInitialLink() or linkStream
File file = await toFile(uriString);
} on UnsupportedError catch (e) {
print(e.message);
} on IOException catch (e) {
print(e);
} catch (e) {
print(e);
}
then you can use this file as you want
Important note
Don't pass uri value like this
File file = await toFile(uri.toString());
Use like this if you are using uni_links package for deep linking purpose. Use getInitialLink() or linkStream
String? uriString = await getInitialLink();
if (uriString != null) {
File file = await toFile(uriString);
}
linkStream.listen((uriString) async {
if (uriString != null) {
File file = await toFile(uriString!);
}
});
This will not modify the uri string as we are not using uri.toString()
So this package will work fine
Working example:
Working example
For more details: uri_to_file
According to the doc you can use the fromUri constructor: File.fromUri(Uri uri).
Your case:
File imageFile = File.fromUri("content://media/external/images/media/138501");
You can use Absolute path plugin.
final filePath = await FlutterAbsolutePath.getAbsolutePath(uriString);
and then show the image by using Image.file:
Image.file(
File(filePath),
);
Make use of flutter_absolute_path package.
flutter_absolute_path: ^1.0.6 In pubsec.yaml

To convert file path from this format : “content://media/external/images/media/5275” To
"/storage/emulated/0/DCIM/Camera/IMG_00124.jpg”
final filePath = await FlutterAbsolutePath.getAbsolutePath("Any path
here");
File tempFile = File(filePath);
if (tempFile.existsSync()) {
//add your logic here.
}
define your URL:
final url = "Your Image Url";
then convert the Image Url to File in flutter :
XFile _xFile = XFile(url);
Done.
You could use Image.file constructor.
DecorationImage(
image: Image.file(File("content://media/external/images/media/138501")),
fit: BoxFit.fill
)
Please take a note: On Android, this may require the android.permission.READ_EXTERNAL_STORAGE permission.